Merge "Generated EnumForVehicleProperty.java from VehicleProeprty.aidl" into main
diff --git a/apexkey/OWNERS b/apexkey/OWNERS
new file mode 100644
index 0000000..38765f9
--- /dev/null
+++ b/apexkey/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 296524155
+
+jooyung@google.com
diff --git a/atrace/1.0/vts/functional/OWNERS b/atrace/OWNERS
similarity index 97%
rename from atrace/1.0/vts/functional/OWNERS
rename to atrace/OWNERS
index 31043aa..d76ffa6 100644
--- a/atrace/1.0/vts/functional/OWNERS
+++ b/atrace/OWNERS
@@ -1,2 +1,3 @@
 # Bug component: 837454
+
 wvw@google.com
diff --git a/audio/aidl/default/Configuration.cpp b/audio/aidl/default/Configuration.cpp
index 9131935..3c3dadb 100644
--- a/audio/aidl/default/Configuration.cpp
+++ b/audio/aidl/default/Configuration.cpp
@@ -105,15 +105,11 @@
     return port;
 }
 
-static AudioPortConfig createPortConfig(int32_t id, int32_t portId, PcmType pcmType, int32_t layout,
-                                        int32_t sampleRate, int32_t flags, bool isInput,
-                                        const AudioPortExt& ext) {
+static AudioPortConfig createDynamicPortConfig(int32_t id, int32_t portId, int32_t flags,
+                                               bool isInput, const AudioPortExt& ext) {
     AudioPortConfig config;
     config.id = id;
     config.portId = portId;
-    config.sampleRate = Int{.value = sampleRate};
-    config.channelMask = AudioChannelLayout::make<AudioChannelLayout::layoutMask>(layout);
-    config.format = AudioFormatDescription{.type = AudioFormatType::PCM, .pcm = pcmType};
     config.gain = AudioGainConfig();
     config.flags = isInput ? AudioIoFlags::make<AudioIoFlags::Tag::input>(flags)
                            : AudioIoFlags::make<AudioIoFlags::Tag::output>(flags);
@@ -121,6 +117,16 @@
     return config;
 }
 
+static AudioPortConfig createPortConfig(int32_t id, int32_t portId, PcmType pcmType, int32_t layout,
+                                        int32_t sampleRate, int32_t flags, bool isInput,
+                                        const AudioPortExt& ext) {
+    AudioPortConfig config = createDynamicPortConfig(id, portId, flags, isInput, ext);
+    config.sampleRate = Int{.value = sampleRate};
+    config.channelMask = AudioChannelLayout::make<AudioChannelLayout::layoutMask>(layout);
+    config.format = AudioFormatDescription{.type = AudioFormatType::PCM, .pcm = pcmType};
+    return config;
+}
+
 static AudioRoute createRoute(const std::vector<AudioPort>& sources, const AudioPort& sink) {
     AudioRoute route;
     route.sinkPortId = sink.id;
@@ -147,8 +153,7 @@
 //  * "primary output", PRIMARY, 1 max open, 1 max active stream
 //    - profile PCM 16-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
 //  * "primary input", 1 max open, 1 max active stream
-//    - profile PCM 16-bit; MONO, STEREO;
-//        8000, 11025, 16000, 32000, 44100, 48000
+//    - profile PCM 16-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
 //  * "telephony_tx", 1 max open, 1 max active stream
 //    - profile PCM 16-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
 //  * "telephony_rx", 1 max open, 1 max active stream
@@ -164,11 +169,11 @@
 //  "FM Tuner" -> "fm_tuner"
 //
 // Initial port configs:
-//  * "Speaker" device port: PCM 16-bit; STEREO; 48000
-//  * "Built-In Mic" device port: PCM 16-bit; MONO; 48000
-//  * "Telephony Tx" device port: PCM 16-bit; MONO; 48000
-//  * "Telephony Rx" device port: PCM 16-bit; MONO; 48000
-//  * "FM Tuner" device port: PCM 16-bit; STEREO; 48000
+//  * "Speaker" device port: dynamic configuration
+//  * "Built-In Mic" device port: dynamic configuration
+//  * "Telephony Tx" device port: dynamic configuration
+//  * "Telephony Rx" device port: dynamic configuration
+//  * "FM Tuner" device port: dynamic configuration
 //
 std::unique_ptr<Configuration> getPrimaryConfiguration() {
     static const Configuration configuration = []() {
@@ -186,9 +191,8 @@
                                            1 << AudioPortDeviceExt::FLAG_INDEX_DEFAULT_DEVICE));
         c.ports.push_back(speakerOutDevice);
         c.initialConfigs.push_back(
-                createPortConfig(speakerOutDevice.id, speakerOutDevice.id, PcmType::INT_16_BIT,
-                                 AudioChannelLayout::LAYOUT_STEREO, 48000, 0, false,
-                                 createDeviceExt(AudioDeviceType::OUT_SPEAKER, 0)));
+                createDynamicPortConfig(speakerOutDevice.id, speakerOutDevice.id, 0, false,
+                                        createDeviceExt(AudioDeviceType::OUT_SPEAKER, 0)));
 
         AudioPort micInDevice =
                 createPort(c.nextPortId++, "Built-In Mic", 0, true,
@@ -196,35 +200,31 @@
                                            1 << AudioPortDeviceExt::FLAG_INDEX_DEFAULT_DEVICE));
         c.ports.push_back(micInDevice);
         c.initialConfigs.push_back(
-                createPortConfig(micInDevice.id, micInDevice.id, PcmType::INT_16_BIT,
-                                 AudioChannelLayout::LAYOUT_MONO, 48000, 0, true,
-                                 createDeviceExt(AudioDeviceType::IN_MICROPHONE, 0)));
+                createDynamicPortConfig(micInDevice.id, micInDevice.id, 0, true,
+                                        createDeviceExt(AudioDeviceType::IN_MICROPHONE, 0)));
 
         AudioPort telephonyTxOutDevice =
                 createPort(c.nextPortId++, "Telephony Tx", 0, false,
                            createDeviceExt(AudioDeviceType::OUT_TELEPHONY_TX, 0));
         c.ports.push_back(telephonyTxOutDevice);
         c.initialConfigs.push_back(
-                createPortConfig(telephonyTxOutDevice.id, telephonyTxOutDevice.id,
-                                 PcmType::INT_16_BIT, AudioChannelLayout::LAYOUT_MONO, 48000, 0,
-                                 false, createDeviceExt(AudioDeviceType::OUT_TELEPHONY_TX, 0)));
+                createDynamicPortConfig(telephonyTxOutDevice.id, telephonyTxOutDevice.id, 0, false,
+                                        createDeviceExt(AudioDeviceType::OUT_TELEPHONY_TX, 0)));
 
         AudioPort telephonyRxInDevice =
                 createPort(c.nextPortId++, "Telephony Rx", 0, true,
                            createDeviceExt(AudioDeviceType::IN_TELEPHONY_RX, 0));
         c.ports.push_back(telephonyRxInDevice);
         c.initialConfigs.push_back(
-                createPortConfig(telephonyRxInDevice.id, telephonyRxInDevice.id,
-                                 PcmType::INT_16_BIT, AudioChannelLayout::LAYOUT_MONO, 48000, 0,
-                                 true, createDeviceExt(AudioDeviceType::IN_TELEPHONY_RX, 0)));
+                createDynamicPortConfig(telephonyRxInDevice.id, telephonyRxInDevice.id, 0, true,
+                                        createDeviceExt(AudioDeviceType::IN_TELEPHONY_RX, 0)));
 
         AudioPort fmTunerInDevice = createPort(c.nextPortId++, "FM Tuner", 0, true,
                                                createDeviceExt(AudioDeviceType::IN_FM_TUNER, 0));
         c.ports.push_back(fmTunerInDevice);
         c.initialConfigs.push_back(
-                createPortConfig(fmTunerInDevice.id, fmTunerInDevice.id, PcmType::INT_16_BIT,
-                                 AudioChannelLayout::LAYOUT_STEREO, 48000, 0, true,
-                                 createDeviceExt(AudioDeviceType::IN_FM_TUNER, 0)));
+                createDynamicPortConfig(fmTunerInDevice.id, fmTunerInDevice.id, 0, true,
+                                        createDeviceExt(AudioDeviceType::IN_FM_TUNER, 0)));
 
         // Mix ports
 
@@ -237,7 +237,7 @@
         c.ports.push_back(primaryOutMix);
 
         AudioPort primaryInMix =
-                createPort(c.nextPortId++, "primary input", 0, true, createPortMixExt(0, 0));
+                createPort(c.nextPortId++, "primary input", 0, true, createPortMixExt(0, 1));
         primaryInMix.profiles.push_back(
                 createProfile(PcmType::INT_16_BIT,
                               {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO},
@@ -252,14 +252,14 @@
         c.ports.push_back(telephonyTxOutMix);
 
         AudioPort telephonyRxInMix =
-                createPort(c.nextPortId++, "telephony_rx", 0, true, createPortMixExt(1, 1));
+                createPort(c.nextPortId++, "telephony_rx", 0, true, createPortMixExt(0, 1));
         telephonyRxInMix.profiles.insert(telephonyRxInMix.profiles.begin(),
                                          standardPcmAudioProfiles.begin(),
                                          standardPcmAudioProfiles.end());
         c.ports.push_back(telephonyRxInMix);
 
         AudioPort fmTunerInMix =
-                createPort(c.nextPortId++, "fm_tuner", 0, true, createPortMixExt(1, 1));
+                createPort(c.nextPortId++, "fm_tuner", 0, true, createPortMixExt(0, 1));
         fmTunerInMix.profiles.insert(fmTunerInMix.profiles.begin(),
                                      standardPcmAudioProfiles.begin(),
                                      standardPcmAudioProfiles.end());
@@ -285,6 +285,22 @@
     return std::make_unique<Configuration>(configuration);
 }
 
+// Note: When transitioning to loading of XML configs, either keep the configuration
+// of the remote submix sources from this static configuration, or update the XML
+// config to match it. There are several reasons for that:
+//   1. The "Remote Submix In" device is listed in the XML config as "attached",
+//      however in the AIDL scheme its device type has a "virtual" connection.
+//   2. The canonical r_submix configuration only lists 'STEREO' and '48000',
+//      however the framework attempts to open streams for other sample rates
+//      as well. The legacy r_submix implementation allowed that, but libaudiohal@aidl
+//      will not find a mix port to use. Because of that, list all channel
+//      masks and sample rates that the legacy implementation allowed.
+//   3. The legacy implementation had a hard limit on the number of routes (10),
+//      and this is checked indirectly by AudioPlaybackCaptureTest#testPlaybackCaptureDoS
+//      CTS test. Instead of hardcoding the number of routes, we can use
+//      "maxOpen/ActiveStreamCount" to enforce a similar limit. However, the canonical
+//      XML file lacks this specification.
+//
 // Remote Submix configuration:
 //
 // Device ports:
@@ -294,16 +310,10 @@
 //    - no profiles specified
 //
 // Mix ports:
-//  * "r_submix output", unlimited max open, unlimited max active stream
+//  * "r_submix output", maximum 20 opened streams, maximum 10 active streams
 //    - profile PCM 16-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
-//    - profile PCM 24-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
-//    - profile PCM 32-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
-//    - profile PCM 32-bit float; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
-//  * "r_submix input", unlimited max open, unlimited max active stream
+//  * "r_submix input", maximum 20 opened streams, maximum 10 active streams
 //    - profile PCM 16-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
-//    - profile PCM 24-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
-//    - profile PCM 32-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
-//    - profile PCM 32-bit float; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
 //
 // Routes:
 //  "r_submix output" -> "Remote Submix Out"
@@ -313,15 +323,6 @@
     static const Configuration configuration = []() {
         Configuration c;
         const std::vector<AudioProfile> standardPcmAudioProfiles{
-                createProfile(PcmType::FLOAT_32_BIT,
-                              {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO},
-                              {8000, 11025, 16000, 32000, 44100, 48000}),
-                createProfile(PcmType::INT_32_BIT,
-                              {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO},
-                              {8000, 11025, 16000, 32000, 44100, 48000}),
-                createProfile(PcmType::INT_24_BIT,
-                              {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO},
-                              {8000, 11025, 16000, 32000, 44100, 48000}),
                 createProfile(PcmType::INT_16_BIT,
                               {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO},
                               {8000, 11025, 16000, 32000, 44100, 48000})};
@@ -345,12 +346,12 @@
         // Mix ports
 
         AudioPort rsubmixOutMix =
-                createPort(c.nextPortId++, "r_submix output", 0, false, createPortMixExt(0, 0));
+                createPort(c.nextPortId++, "r_submix output", 0, false, createPortMixExt(20, 10));
         rsubmixOutMix.profiles = standardPcmAudioProfiles;
         c.ports.push_back(rsubmixOutMix);
 
         AudioPort rsubmixInMix =
-                createPort(c.nextPortId++, "r_submix input", 0, true, createPortMixExt(0, 0));
+                createPort(c.nextPortId++, "r_submix input", 0, true, createPortMixExt(20, 10));
         rsubmixInMix.profiles = standardPcmAudioProfiles;
         c.ports.push_back(rsubmixInMix);
 
@@ -385,7 +386,7 @@
 //  * "usb_device output" -> "USB Headset Out"
 //  * "USB Device In", "USB Headset In" -> "usb_device input"
 //
-// Profiles for device port connected state:
+// Profiles for device port connected state (when simulating connections):
 //  * "USB Device Out", "USB Headset Out":
 //    - profile PCM 16-bit; MONO, STEREO, INDEX_MASK_1, INDEX_MASK_2; 44100, 48000
 //    - profile PCM 24-bit; MONO, STEREO, INDEX_MASK_1, INDEX_MASK_2; 44100, 48000
@@ -442,7 +443,7 @@
         c.ports.push_back(usbDeviceOutMix);
 
         AudioPort usbDeviceInMix =
-                createPort(c.nextPortId++, "usb_device input", 0, true, createPortMixExt(1, 1));
+                createPort(c.nextPortId++, "usb_device input", 0, true, createPortMixExt(0, 1));
         c.ports.push_back(usbDeviceInMix);
 
         c.routes.push_back(createRoute({usbDeviceOutMix}, usbOutDevice));
@@ -461,6 +462,10 @@
 //    - no profiles specified
 //  * "Test In", IN_AFE_PROXY
 //    - no profiles specified
+//  * "Wired Headset", OUT_HEADSET
+//    - no profiles specified
+//  * "Wired Headset Mic", IN_HEADSET
+//    - no profiles specified
 //
 // Mix ports:
 //  * "test output", 1 max open, 1 max active stream
@@ -476,12 +481,17 @@
 //
 // Routes:
 //  "test output", "test fast output", "test compressed offload" -> "Test Out"
-//  "Test In" -> "test input"
+//  "test output" -> "Wired Headset"
+//  "Test In", "Wired Headset Mic" -> "test input"
 //
 // Initial port configs:
 //  * "Test Out" device port: PCM 24-bit; STEREO; 48000
 //  * "Test In" device port: PCM 24-bit; MONO; 48000
 //
+// Profiles for device port connected state (when simulating connections):
+//  * "Wired Headset": dynamic profiles
+//  * "Wired Headset Mic": dynamic profiles
+//
 std::unique_ptr<Configuration> getStubConfiguration() {
     static const Configuration configuration = []() {
         Configuration c;
@@ -496,6 +506,12 @@
                                  AudioChannelLayout::LAYOUT_STEREO, 48000, 0, false,
                                  createDeviceExt(AudioDeviceType::OUT_AFE_PROXY, 0)));
 
+        AudioPort headsetOutDevice =
+                createPort(c.nextPortId++, "Wired Headset", 0, false,
+                           createDeviceExt(AudioDeviceType::OUT_HEADSET, 0,
+                                           AudioDeviceDescription::CONNECTION_ANALOG));
+        c.ports.push_back(headsetOutDevice);
+
         AudioPort testInDevice = createPort(c.nextPortId++, "Test In", 0, true,
                                             createDeviceExt(AudioDeviceType::IN_AFE_PROXY, 0));
         c.ports.push_back(testInDevice);
@@ -504,6 +520,12 @@
                                  AudioChannelLayout::LAYOUT_MONO, 48000, 0, true,
                                  createDeviceExt(AudioDeviceType::IN_AFE_PROXY, 0)));
 
+        AudioPort headsetInDevice =
+                createPort(c.nextPortId++, "Wired Headset Mic", 0, true,
+                           createDeviceExt(AudioDeviceType::IN_HEADSET, 0,
+                                           AudioDeviceDescription::CONNECTION_ANALOG));
+        c.ports.push_back(headsetInDevice);
+
         // Mix ports
 
         AudioPort testOutMix =
@@ -533,23 +555,24 @@
                               {44100, 48000}));
         c.ports.push_back(compressedOffloadOutMix);
 
-        AudioPort testInMIx =
+        AudioPort testInMix =
                 createPort(c.nextPortId++, "test input", 0, true, createPortMixExt(2, 2));
-        testInMIx.profiles.push_back(
+        testInMix.profiles.push_back(
                 createProfile(PcmType::INT_16_BIT,
                               {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO,
                                AudioChannelLayout::LAYOUT_FRONT_BACK},
                               {8000, 11025, 16000, 22050, 32000, 44100, 48000}));
-        testInMIx.profiles.push_back(
+        testInMix.profiles.push_back(
                 createProfile(PcmType::INT_24_BIT,
                               {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO,
                                AudioChannelLayout::LAYOUT_FRONT_BACK},
                               {8000, 11025, 16000, 22050, 32000, 44100, 48000}));
-        c.ports.push_back(testInMIx);
+        c.ports.push_back(testInMix);
 
         c.routes.push_back(
                 createRoute({testOutMix, testFastOutMix, compressedOffloadOutMix}, testOutDevice));
-        c.routes.push_back(createRoute({testInDevice}, testInMIx));
+        c.routes.push_back(createRoute({testOutMix}, headsetOutDevice));
+        c.routes.push_back(createRoute({testInDevice, headsetInDevice}, testInMix));
 
         c.portConfigs.insert(c.portConfigs.end(), c.initialConfigs.begin(), c.initialConfigs.end());
 
@@ -582,11 +605,19 @@
 //  "a2dp output" -> "BT A2DP Speaker"
 //  "hearing aid output" -> "BT Hearing Aid Out"
 //
+// Profiles for device port connected state (when simulating connections):
+//  * "BT A2DP Out", "BT A2DP Headphones", "BT A2DP Speaker":
+//    - profile PCM 16-bit; STEREO; 44100, 48000, 88200, 96000
+//  * "BT Hearing Aid Out":
+//    - profile PCM 16-bit; STEREO; 16000, 24000
+//
 std::unique_ptr<Configuration> getBluetoothConfiguration() {
     static const Configuration configuration = []() {
         const std::vector<AudioProfile> standardPcmAudioProfiles = {
                 createProfile(PcmType::INT_16_BIT, {AudioChannelLayout::LAYOUT_STEREO},
                               {44100, 48000, 88200, 96000})};
+        const std::vector<AudioProfile> hearingAidAudioProfiles = {createProfile(
+                PcmType::INT_16_BIT, {AudioChannelLayout::LAYOUT_STEREO}, {16000, 24000})};
         Configuration c;
 
         // Device ports
@@ -624,8 +655,7 @@
                            createDeviceExt(AudioDeviceType::OUT_HEARING_AID, 0,
                                            AudioDeviceDescription::CONNECTION_WIRELESS));
         c.ports.push_back(btOutHearingAid);
-        c.connectedProfiles[btOutHearingAid.id] = std::vector<AudioProfile>(
-                {createProfile(PcmType::INT_16_BIT, {AudioChannelLayout::LAYOUT_STEREO}, {16000})});
+        c.connectedProfiles[btOutHearingAid.id] = hearingAidAudioProfiles;
 
         // Mix ports
         AudioPort btOutMix =
@@ -634,8 +664,7 @@
 
         AudioPort btHearingOutMix =
                 createPort(c.nextPortId++, "hearing aid output", 0, false, createPortMixExt(1, 1));
-        btHearingOutMix.profiles.push_back(createProfile(
-                PcmType::INT_16_BIT, {AudioChannelLayout::LAYOUT_STEREO}, {16000, 24000}));
+        btHearingOutMix.profiles = hearingAidAudioProfiles;
         c.ports.push_back(btHearingOutMix);
 
         c.routes.push_back(createRoute({btOutMix}, btOutDevice));
diff --git a/audio/aidl/default/EffectThread.cpp b/audio/aidl/default/EffectThread.cpp
index cd2ba53..47ba9f4 100644
--- a/audio/aidl/default/EffectThread.cpp
+++ b/audio/aidl/default/EffectThread.cpp
@@ -48,6 +48,8 @@
     mPriority = priority;
     {
         std::lock_guard lg(mThreadMutex);
+        mStop = true;
+        mExit = false;
         mThreadContext = std::move(context);
         auto statusMQ = mThreadContext->getStatusFmq();
         EventFlag* efGroup = nullptr;
diff --git a/audio/aidl/default/Module.cpp b/audio/aidl/default/Module.cpp
index f81095e..d721b32 100644
--- a/audio/aidl/default/Module.cpp
+++ b/audio/aidl/default/Module.cpp
@@ -65,32 +65,56 @@
 
 namespace {
 
+inline bool hasDynamicChannelMasks(const std::vector<AudioChannelLayout>& channelMasks) {
+    return channelMasks.empty() ||
+           std::all_of(channelMasks.begin(), channelMasks.end(),
+                       [](const auto& channelMask) { return channelMask == AudioChannelLayout{}; });
+}
+
+inline bool hasDynamicFormat(const AudioFormatDescription& format) {
+    return format == AudioFormatDescription{};
+}
+
+inline bool hasDynamicSampleRates(const std::vector<int32_t>& sampleRates) {
+    return sampleRates.empty() ||
+           std::all_of(sampleRates.begin(), sampleRates.end(),
+                       [](const auto& sampleRate) { return sampleRate == 0; });
+}
+
+inline bool isDynamicProfile(const AudioProfile& profile) {
+    return hasDynamicFormat(profile.format) || hasDynamicChannelMasks(profile.channelMasks) ||
+           hasDynamicSampleRates(profile.sampleRates);
+}
+
+bool hasDynamicProfilesOnly(const std::vector<AudioProfile>& profiles) {
+    if (profiles.empty()) return true;
+    return std::all_of(profiles.begin(), profiles.end(), isDynamicProfile);
+}
+
+// Note: does not assign an ID to the config.
 bool generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
+    const bool allowDynamicConfig = port.ext.getTag() == AudioPortExt::device;
     *config = {};
     config->portId = port.id;
-    if (port.profiles.empty()) {
-        LOG(ERROR) << __func__ << ": port " << port.id << " has no profiles";
-        return false;
+    for (const auto& profile : port.profiles) {
+        if (isDynamicProfile(profile)) continue;
+        config->format = profile.format;
+        config->channelMask = *profile.channelMasks.begin();
+        config->sampleRate = Int{.value = *profile.sampleRates.begin()};
+        config->flags = port.flags;
+        config->ext = port.ext;
+        return true;
     }
-    const auto& profile = port.profiles.begin();
-    config->format = profile->format;
-    if (profile->channelMasks.empty()) {
-        LOG(ERROR) << __func__ << ": the first profile in port " << port.id
-                   << " has no channel masks";
-        return false;
+    if (allowDynamicConfig) {
+        config->format = AudioFormatDescription{};
+        config->channelMask = AudioChannelLayout{};
+        config->sampleRate = Int{.value = 0};
+        config->flags = port.flags;
+        config->ext = port.ext;
+        return true;
     }
-    config->channelMask = *profile->channelMasks.begin();
-    if (profile->sampleRates.empty()) {
-        LOG(ERROR) << __func__ << ": the first profile in port " << port.id
-                   << " has no sample rates";
-        return false;
-    }
-    Int sampleRate;
-    sampleRate.value = *profile->sampleRates.begin();
-    config->sampleRate = sampleRate;
-    config->flags = port.flags;
-    config->ext = port.ext;
-    return true;
+    LOG(ERROR) << __func__ << ": port " << port.id << " only has dynamic profiles";
+    return false;
 }
 
 bool findAudioProfile(const AudioPort& port, const AudioFormatDescription& format,
@@ -314,6 +338,18 @@
     return config;
 }
 
+std::vector<AudioRoute*> Module::getAudioRoutesForAudioPortImpl(int32_t portId) {
+    std::vector<AudioRoute*> result;
+    auto& routes = getConfig().routes;
+    for (auto& r : routes) {
+        const auto& srcs = r.sourcePortIds;
+        if (r.sinkPortId == portId || std::find(srcs.begin(), srcs.end(), portId) != srcs.end()) {
+            result.push_back(&r);
+        }
+    }
+    return result;
+}
+
 internal::Configuration& Module::getConfig() {
     if (!mConfig) {
         mConfig = std::move(initializeConfig());
@@ -321,6 +357,24 @@
     return *mConfig;
 }
 
+std::set<int32_t> Module::getRoutableAudioPortIds(int32_t portId,
+                                                  std::vector<AudioRoute*>* routes) {
+    std::vector<AudioRoute*> routesStorage;
+    if (routes == nullptr) {
+        routesStorage = getAudioRoutesForAudioPortImpl(portId);
+        routes = &routesStorage;
+    }
+    std::set<int32_t> result;
+    for (AudioRoute* r : *routes) {
+        if (r->sinkPortId == portId) {
+            result.insert(r->sourcePortIds.begin(), r->sourcePortIds.end());
+        } else {
+            result.insert(r->sinkPortId);
+        }
+    }
+    return result;
+}
+
 void Module::registerPatch(const AudioPatch& patch) {
     auto& configs = getConfig().portConfigs;
     auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
@@ -340,21 +394,43 @@
 
 ndk::ScopedAStatus Module::updateStreamsConnectedState(const AudioPatch& oldPatch,
                                                        const AudioPatch& newPatch) {
-    // Streams from the old patch need to be disconnected, streams from the new
-    // patch need to be connected. If the stream belongs to both patches, no need
-    // to update it.
+    // Notify streams about the new set of devices they are connected to.
     auto maybeFailure = ndk::ScopedAStatus::ok();
-    std::set<int32_t> idsToDisconnect, idsToConnect, idsToDisconnectOnFailure;
-    idsToDisconnect.insert(oldPatch.sourcePortConfigIds.begin(),
-                           oldPatch.sourcePortConfigIds.end());
-    idsToDisconnect.insert(oldPatch.sinkPortConfigIds.begin(), oldPatch.sinkPortConfigIds.end());
-    idsToConnect.insert(newPatch.sourcePortConfigIds.begin(), newPatch.sourcePortConfigIds.end());
-    idsToConnect.insert(newPatch.sinkPortConfigIds.begin(), newPatch.sinkPortConfigIds.end());
-    std::for_each(idsToDisconnect.begin(), idsToDisconnect.end(), [&](const auto& portConfigId) {
-        if (idsToConnect.count(portConfigId) == 0 && mStreams.count(portConfigId) != 0) {
-            if (auto status = mStreams.setStreamConnectedDevices(portConfigId, {}); status.isOk()) {
+    using Connections =
+            std::map<int32_t /*mixPortConfigId*/, std::set<int32_t /*devicePortConfigId*/>>;
+    Connections oldConnections, newConnections;
+    auto fillConnectionsHelper = [&](Connections& connections,
+                                     const std::vector<int32_t>& mixPortCfgIds,
+                                     const std::vector<int32_t>& devicePortCfgIds) {
+        for (int32_t mixPortCfgId : mixPortCfgIds) {
+            connections[mixPortCfgId].insert(devicePortCfgIds.begin(), devicePortCfgIds.end());
+        }
+    };
+    auto fillConnections = [&](Connections& connections, const AudioPatch& patch) {
+        if (std::find_if(patch.sourcePortConfigIds.begin(), patch.sourcePortConfigIds.end(),
+                         [&](int32_t portConfigId) { return mStreams.count(portConfigId) > 0; }) !=
+            patch.sourcePortConfigIds.end()) {
+            // Sources are mix ports.
+            fillConnectionsHelper(connections, patch.sourcePortConfigIds, patch.sinkPortConfigIds);
+        } else if (std::find_if(patch.sinkPortConfigIds.begin(), patch.sinkPortConfigIds.end(),
+                                [&](int32_t portConfigId) {
+                                    return mStreams.count(portConfigId) > 0;
+                                }) != patch.sinkPortConfigIds.end()) {
+            // Sources are device ports.
+            fillConnectionsHelper(connections, patch.sinkPortConfigIds, patch.sourcePortConfigIds);
+        }  // Otherwise, there are no streams to notify.
+    };
+    fillConnections(oldConnections, oldPatch);
+    fillConnections(newConnections, newPatch);
+
+    std::for_each(oldConnections.begin(), oldConnections.end(), [&](const auto& connectionPair) {
+        const int32_t mixPortConfigId = connectionPair.first;
+        if (auto it = newConnections.find(mixPortConfigId);
+            it == newConnections.end() || it->second != connectionPair.second) {
+            if (auto status = mStreams.setStreamConnectedDevices(mixPortConfigId, {});
+                status.isOk()) {
                 LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
-                           << portConfigId << " has been disconnected";
+                           << mixPortConfigId << " has been disconnected";
             } else {
                 // Disconnection is tricky to roll back, just register a failure.
                 maybeFailure = std::move(status);
@@ -362,23 +438,26 @@
         }
     });
     if (!maybeFailure.isOk()) return maybeFailure;
-    std::for_each(idsToConnect.begin(), idsToConnect.end(), [&](const auto& portConfigId) {
-        if (idsToDisconnect.count(portConfigId) == 0 && mStreams.count(portConfigId) != 0) {
-            const auto connectedDevices = findConnectedDevices(portConfigId);
+    std::set<int32_t> idsToDisconnectOnFailure;
+    std::for_each(newConnections.begin(), newConnections.end(), [&](const auto& connectionPair) {
+        const int32_t mixPortConfigId = connectionPair.first;
+        if (auto it = oldConnections.find(mixPortConfigId);
+            it == oldConnections.end() || it->second != connectionPair.second) {
+            const auto connectedDevices = findConnectedDevices(mixPortConfigId);
             if (connectedDevices.empty()) {
                 // This is important as workers use the vector size to derive the connection status.
                 LOG(FATAL) << "updateStreamsConnectedState: No connected devices found for port "
                               "config id "
-                           << portConfigId;
+                           << mixPortConfigId;
             }
-            if (auto status = mStreams.setStreamConnectedDevices(portConfigId, connectedDevices);
+            if (auto status = mStreams.setStreamConnectedDevices(mixPortConfigId, connectedDevices);
                 status.isOk()) {
                 LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
-                           << portConfigId << " has been connected to: "
+                           << mixPortConfigId << " has been connected to: "
                            << ::android::internal::ToString(connectedDevices);
             } else {
                 maybeFailure = std::move(status);
-                idsToDisconnectOnFailure.insert(portConfigId);
+                idsToDisconnectOnFailure.insert(mixPortConfigId);
             }
         }
     });
@@ -454,16 +533,15 @@
             LOG(ERROR) << __func__ << ": port id " << templateId << " is not a device port";
             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
         }
-        if (!templateIt->profiles.empty()) {
-            LOG(ERROR) << __func__ << ": port id " << templateId
-                       << " does not have dynamic profiles";
-            return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
-        }
         auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
         if (templateDevicePort.device.type.connection.empty()) {
             LOG(ERROR) << __func__ << ": port id " << templateId << " is permanently attached";
             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
         }
+        if (mConnectedDevicePorts.find(templateId) != mConnectedDevicePorts.end()) {
+            LOG(ERROR) << __func__ << ": port id " << templateId << " is a connected device port";
+            return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+        }
         // Postpone id allocation until we ensure that there are no client errors.
         connectedPort = *templateIt;
         connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
@@ -486,70 +564,101 @@
         }
     }
 
-    if (!mDebug.simulateDeviceConnections) {
-        RETURN_STATUS_IF_ERROR(populateConnectedDevicePort(&connectedPort));
-    } else {
-        auto& connectedProfiles = getConfig().connectedProfiles;
-        if (auto connectedProfilesIt = connectedProfiles.find(templateId);
-            connectedProfilesIt != connectedProfiles.end()) {
-            connectedPort.profiles = connectedProfilesIt->second;
-        }
-    }
-    if (connectedPort.profiles.empty()) {
-        LOG(ERROR) << "Profiles of a connected port still empty after connecting external device "
-                   << connectedPort.toString();
-        return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
-    }
+    // Two main cases are considered with regard to the profiles of the connected device port:
+    //
+    //  1. If the template device port has dynamic profiles, and at least one routable mix
+    //     port also has dynamic profiles, it means that after connecting the device, the
+    //     connected device port must have profiles populated with actual capabilities of
+    //     the connected device, and dynamic of routable mix ports will be filled
+    //     according to these capabilities. An example of this case is connection of an
+    //     HDMI or USB device. For USB handled by ADSP, there can be mix ports with static
+    //     profiles, and one dedicated mix port for "hi-fi" playback. The latter is left with
+    //     dynamic profiles so that they can be populated with actual capabilities of
+    //     the connected device.
+    //
+    //  2. If the template device port has dynamic profiles, while all routable mix ports
+    //     have static profiles, it means that after connecting the device, the connected
+    //     device port can be left with dynamic profiles, and profiles of mix ports are
+    //     left untouched. An example of this case is connection of an analog wired
+    //     headset, it should be treated in the same way as a speaker.
+    //
+    //  Yet another possible case is when both the template device port and all routable
+    //  mix ports have static profiles. This is allowed and handled correctly, however, it
+    //  is not very practical, since these profiles are likely duplicates of each other.
 
-    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);
+    std::vector<AudioRoute*> routesToMixPorts = getAudioRoutesForAudioPortImpl(templateId);
+    std::set<int32_t> routableMixPortIds = getRoutableAudioPortIds(templateId, &routesToMixPorts);
+    if (hasDynamicProfilesOnly(connectedPort.profiles)) {
+        if (!mDebug.simulateDeviceConnections) {
+            RETURN_STATUS_IF_ERROR(populateConnectedDevicePort(&connectedPort));
+        } else {
+            auto& connectedProfiles = getConfig().connectedProfiles;
+            if (auto connectedProfilesIt = connectedProfiles.find(templateId);
+                connectedProfilesIt != connectedProfiles.end()) {
+                connectedPort.profiles = connectedProfilesIt->second;
+            }
         }
-        if (profile.sampleRates.empty()) {
-            LOG(ERROR) << __func__ << ": the profile " << profile.name << " has no sample rates";
-            return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+        if (hasDynamicProfilesOnly(connectedPort.profiles)) {
+            // Possible case 2. Check if all routable mix ports have static profiles.
+            if (auto dynamicMixPortIt = std::find_if(ports.begin(), ports.end(),
+                                                     [&routableMixPortIds](const auto& p) {
+                                                         return routableMixPortIds.count(p.id) >
+                                                                        0 &&
+                                                                hasDynamicProfilesOnly(p.profiles);
+                                                     });
+                dynamicMixPortIt != ports.end()) {
+                LOG(ERROR) << __func__
+                           << ": connected port only has dynamic profiles after connecting "
+                           << "external device " << connectedPort.toString() << ", and there exist "
+                           << "a routable mix port with dynamic profiles: "
+                           << dynamicMixPortIt->toString();
+                return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+            }
         }
     }
 
-    connectedPort.id = ++getConfig().nextPortId;
+    connectedPort.id = getConfig().nextPortId++;
     auto [connectedPortsIt, _] =
-            mConnectedDevicePorts.insert(std::pair(connectedPort.id, std::vector<int32_t>()));
+            mConnectedDevicePorts.insert(std::pair(connectedPort.id, std::set<int32_t>()));
     LOG(DEBUG) << __func__ << ": template port " << templateId << " external device connected, "
                << "connected port ID " << connectedPort.id;
     ports.push_back(connectedPort);
     onExternalDeviceConnectionChanged(connectedPort, true /*connected*/);
 
-    std::vector<int32_t> routablePortIds;
+    // For routes where the template port is a source, add the connected port to sources,
+    // otherwise, create a new route by copying from the route for the template port.
     std::vector<AudioRoute> newRoutes;
-    auto& routes = getConfig().routes;
-    for (auto& r : routes) {
-        if (r.sinkPortId == templateId) {
-            AudioRoute newRoute;
-            newRoute.sourcePortIds = r.sourcePortIds;
-            newRoute.sinkPortId = connectedPort.id;
-            newRoute.isExclusive = r.isExclusive;
-            newRoutes.push_back(std::move(newRoute));
-            routablePortIds.insert(routablePortIds.end(), r.sourcePortIds.begin(),
-                                   r.sourcePortIds.end());
+    for (AudioRoute* r : routesToMixPorts) {
+        if (r->sinkPortId == templateId) {
+            newRoutes.push_back(AudioRoute{.sourcePortIds = r->sourcePortIds,
+                                           .sinkPortId = connectedPort.id,
+                                           .isExclusive = r->isExclusive});
         } else {
-            auto& srcs = r.sourcePortIds;
-            if (std::find(srcs.begin(), srcs.end(), templateId) != srcs.end()) {
-                srcs.push_back(connectedPort.id);
-                routablePortIds.push_back(r.sinkPortId);
-            }
+            r->sourcePortIds.push_back(connectedPort.id);
         }
     }
+    auto& routes = getConfig().routes;
     routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
 
-    // Note: this is a simplistic approach assuming that a mix port can only be populated
-    // from a single device port. Implementing support for stuffing dynamic profiles with a superset
-    // of all profiles from all routable dynamic device ports would be more involved.
-    for (const auto mixPortId : routablePortIds) {
-        auto portsIt = findById<AudioPort>(ports, mixPortId);
-        if (portsIt != ports.end() && portsIt->profiles.empty()) {
-            portsIt->profiles = connectedPort.profiles;
-            connectedPortsIt->second.push_back(portsIt->id);
+    if (!hasDynamicProfilesOnly(connectedPort.profiles) && !routableMixPortIds.empty()) {
+        // Note: this is a simplistic approach assuming that a mix port can only be populated
+        // from a single device port. Implementing support for stuffing dynamic profiles with
+        // a superset of all profiles from all routable dynamic device ports would be more involved.
+        for (auto& port : ports) {
+            if (routableMixPortIds.count(port.id) == 0) continue;
+            if (hasDynamicProfilesOnly(port.profiles)) {
+                port.profiles = connectedPort.profiles;
+                connectedPortsIt->second.insert(port.id);
+            } else {
+                // Check if profiles are not all dynamic because they were populated by
+                // a previous connection. Otherwise, it means that they are actually static.
+                for (const auto& cp : mConnectedDevicePorts) {
+                    if (cp.second.count(port.id) > 0) {
+                        connectedPortsIt->second.insert(port.id);
+                        break;
+                    }
+                }
+            }
         }
     }
     *_aidl_return = std::move(connectedPort);
@@ -604,13 +713,20 @@
         }
     }
 
-    for (const auto mixPortId : connectedPortsIt->second) {
+    // Clear profiles for mix ports that are not connected to any other ports.
+    std::set<int32_t> mixPortsToClear = std::move(connectedPortsIt->second);
+    mConnectedDevicePorts.erase(connectedPortsIt);
+    for (const auto& connectedPort : mConnectedDevicePorts) {
+        for (int32_t mixPortId : connectedPort.second) {
+            mixPortsToClear.erase(mixPortId);
+        }
+    }
+    for (int32_t mixPortId : mixPortsToClear) {
         auto mixPortIt = findById<AudioPort>(ports, mixPortId);
         if (mixPortIt != ports.end()) {
             mixPortIt->profiles = {};
         }
     }
-    mConnectedDevicePorts.erase(connectedPortsIt);
 
     return ndk::ScopedAStatus::ok();
 }
@@ -658,13 +774,9 @@
         LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
     }
-    auto& routes = getConfig().routes;
-    std::copy_if(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
-                 [&](const auto& r) {
-                     const auto& srcs = r.sourcePortIds;
-                     return r.sinkPortId == in_portId ||
-                            std::find(srcs.begin(), srcs.end(), in_portId) != srcs.end();
-                 });
+    std::vector<AudioRoute*> routes = getAudioRoutesForAudioPortImpl(in_portId);
+    std::transform(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
+                   [](auto rptr) { return *rptr; });
     return ndk::ScopedAStatus::ok();
 }
 
@@ -843,6 +955,7 @@
         patches.push_back(*_aidl_return);
     } else {
         oldPatch = *existing;
+        *existing = *_aidl_return;
     }
     patchesBackup = mPatches;
     registerPatch(*_aidl_return);
@@ -877,13 +990,14 @@
 
     const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
     if (portId == 0) {
-        LOG(ERROR) << __func__ << ": input port config does not specify portId";
+        LOG(ERROR) << __func__ << ": requested port config does not specify portId";
         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
     }
     auto& ports = getConfig().ports;
     auto portIt = findById<AudioPort>(ports, portId);
     if (portIt == ports.end()) {
-        LOG(ERROR) << __func__ << ": input port config points to non-existent portId " << portId;
+        LOG(ERROR) << __func__ << ": requested port config points to non-existent portId "
+                   << portId;
         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
     }
     if (existing != configs.end()) {
@@ -901,6 +1015,10 @@
     // or a new generated config. Now attempt to update it according to the specified
     // fields of 'in_requested'.
 
+    // Device ports with only dynamic profiles are used for devices that are connected via ADSP,
+    // which takes care of their actual configuration automatically.
+    const bool allowDynamicConfig = portIt->ext.getTag() == AudioPortExt::device &&
+                                    hasDynamicProfilesOnly(portIt->profiles);
     bool requestedIsValid = true, requestedIsFullySpecified = true;
 
     AudioIoFlags portFlags = portIt->flags;
@@ -918,17 +1036,19 @@
     AudioProfile portProfile;
     if (in_requested.format.has_value()) {
         const auto& format = in_requested.format.value();
-        if (findAudioProfile(*portIt, format, &portProfile)) {
+        if ((format == AudioFormatDescription{} && allowDynamicConfig) ||
+            findAudioProfile(*portIt, format, &portProfile)) {
             out_suggested->format = format;
         } else {
             LOG(WARNING) << __func__ << ": requested format " << format.toString()
-                         << " is not found in port's " << portId << " profiles";
+                         << " is not found in the profiles of port " << portId;
             requestedIsValid = false;
         }
     } else {
         requestedIsFullySpecified = false;
     }
-    if (!findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
+    if (!(out_suggested->format.value() == AudioFormatDescription{} && allowDynamicConfig) &&
+        !findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
         LOG(ERROR) << __func__ << ": port " << portId << " does not support format "
                    << out_suggested->format.value().toString() << " anymore";
         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
@@ -936,8 +1056,9 @@
 
     if (in_requested.channelMask.has_value()) {
         const auto& channelMask = in_requested.channelMask.value();
-        if (find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
-            portProfile.channelMasks.end()) {
+        if ((channelMask == AudioChannelLayout{} && allowDynamicConfig) ||
+            find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
+                    portProfile.channelMasks.end()) {
             out_suggested->channelMask = channelMask;
         } else {
             LOG(WARNING) << __func__ << ": requested channel mask " << channelMask.toString()
@@ -951,7 +1072,8 @@
 
     if (in_requested.sampleRate.has_value()) {
         const auto& sampleRate = in_requested.sampleRate.value();
-        if (find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
+        if ((sampleRate.value == 0 && allowDynamicConfig) ||
+            find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
                  sampleRate.value) != portProfile.sampleRates.end()) {
             out_suggested->sampleRate = sampleRate;
         } else {
@@ -1255,6 +1377,12 @@
             mmapSources.insert(port.id);
         }
     }
+    if (mmapSources.empty() && mmapSinks.empty()) {
+        AudioMMapPolicyInfo never;
+        never.mmapPolicy = AudioMMapPolicy::NEVER;
+        _aidl_return->push_back(never);
+        return ndk::ScopedAStatus::ok();
+    }
     for (const auto& route : getConfig().routes) {
         if (mmapSinks.count(route.sinkPortId) != 0) {
             // The sink is a mix port, add the sources if they are device ports.
@@ -1343,7 +1471,18 @@
     return mIsMmapSupported.value();
 }
 
-ndk::ScopedAStatus Module::populateConnectedDevicePort(AudioPort* audioPort __unused) {
+ndk::ScopedAStatus Module::populateConnectedDevicePort(AudioPort* audioPort) {
+    if (audioPort->ext.getTag() != AudioPortExt::device) {
+        LOG(ERROR) << __func__ << ": not a device port: " << audioPort->toString();
+        return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+    }
+    const auto& devicePort = audioPort->ext.get<AudioPortExt::device>();
+    if (!devicePort.device.type.connection.empty()) {
+        LOG(ERROR) << __func__
+                   << ": module implementation must override 'populateConnectedDevicePort' "
+                   << "to handle connection of external devices.";
+        return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+    }
     LOG(VERBOSE) << __func__ << ": do nothing and return ok";
     return ndk::ScopedAStatus::ok();
 }
diff --git a/audio/aidl/default/Stream.cpp b/audio/aidl/default/Stream.cpp
index af89f5f..f7298c0 100644
--- a/audio/aidl/default/Stream.cpp
+++ b/audio/aidl/default/Stream.cpp
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include <pthread.h>
+
 #define LOG_TAG "AHAL_Stream"
 #include <android-base/logging.h>
 #include <android/binder_ibinder_platform.h>
@@ -94,6 +96,14 @@
     mDataMQ.reset();
 }
 
+pid_t StreamWorkerCommonLogic::getTid() const {
+#if defined(__ANDROID__)
+    return pthread_gettid_np(pthread_self());
+#else
+    return 0;
+#endif
+}
+
 std::string StreamWorkerCommonLogic::init() {
     if (mContext->getCommandMQ() == nullptr) return "Command MQ is null";
     if (mContext->getReplyMQ() == nullptr) return "Reply MQ is null";
@@ -164,7 +174,7 @@
     switch (command.getTag()) {
         case Tag::halReservedExit:
             if (const int32_t cookie = command.get<Tag::halReservedExit>();
-                cookie == mContext->getInternalCommandCookie()) {
+                cookie == (mContext->getInternalCommandCookie() ^ getTid())) {
                 mDriver->shutdown();
                 setClosed();
                 // This is an internal command, no need to reply.
@@ -384,7 +394,7 @@
     switch (command.getTag()) {
         case Tag::halReservedExit:
             if (const int32_t cookie = command.get<Tag::halReservedExit>();
-                cookie == mContext->getInternalCommandCookie()) {
+                cookie == (mContext->getInternalCommandCookie() ^ getTid())) {
                 mDriver->shutdown();
                 setClosed();
                 // This is an internal command, no need to reply.
@@ -717,7 +727,7 @@
     if (auto commandMQ = mContext.getCommandMQ(); commandMQ != nullptr) {
         LOG(DEBUG) << __func__ << ": asking the worker to exit...";
         auto cmd = StreamDescriptor::Command::make<StreamDescriptor::Command::Tag::halReservedExit>(
-                mContext.getInternalCommandCookie());
+                mContext.getInternalCommandCookie() ^ mWorker->getTid());
         // Note: never call 'pause' and 'resume' methods of StreamWorker
         // in the HAL implementation. These methods are to be used by
         // the client side only. Preventing the worker loop from running
diff --git a/audio/aidl/default/alsa/ModuleAlsa.cpp b/audio/aidl/default/alsa/ModuleAlsa.cpp
index 8e75d56..8512631 100644
--- a/audio/aidl/default/alsa/ModuleAlsa.cpp
+++ b/audio/aidl/default/alsa/ModuleAlsa.cpp
@@ -39,13 +39,14 @@
     if (!deviceProfile.has_value()) {
         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
     }
-    auto profile = alsa::readAlsaDeviceInfo(*deviceProfile);
-    if (!profile.has_value()) {
+    auto proxy = alsa::readAlsaDeviceInfo(*deviceProfile);
+    if (proxy.get() == nullptr) {
         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
     }
 
-    std::vector<AudioChannelLayout> channels = alsa::getChannelMasksFromProfile(&profile.value());
-    std::vector<int> sampleRates = alsa::getSampleRatesFromProfile(&profile.value());
+    alsa_device_profile* profile = proxy.getProfile();
+    std::vector<AudioChannelLayout> channels = alsa::getChannelMasksFromProfile(profile);
+    std::vector<int> sampleRates = alsa::getSampleRatesFromProfile(profile);
 
     for (size_t i = 0; i < std::min(MAX_PROFILE_FORMATS, AUDIO_PORT_MAX_AUDIO_PROFILES) &&
                        profile->formats[i] != PCM_FORMAT_INVALID;
diff --git a/audio/aidl/default/alsa/StreamAlsa.cpp b/audio/aidl/default/alsa/StreamAlsa.cpp
index 0605d6f..403b94b 100644
--- a/audio/aidl/default/alsa/StreamAlsa.cpp
+++ b/audio/aidl/default/alsa/StreamAlsa.cpp
@@ -83,7 +83,7 @@
             proxy = alsa::openProxyForAttachedDevice(
                     device, const_cast<struct pcm_config*>(&mConfig.value()), mBufferSizeFrames);
         }
-        if (!proxy) {
+        if (proxy.get() == nullptr) {
             return ::android::NO_INIT;
         }
         alsaDeviceProxies.push_back(std::move(proxy));
diff --git a/audio/aidl/default/alsa/Utils.cpp b/audio/aidl/default/alsa/Utils.cpp
index 9dcd024..c08836c 100644
--- a/audio/aidl/default/alsa/Utils.cpp
+++ b/audio/aidl/default/alsa/Utils.cpp
@@ -37,6 +37,23 @@
 
 namespace aidl::android::hardware::audio::core::alsa {
 
+DeviceProxy::DeviceProxy() : mProfile(nullptr), mProxy(nullptr, alsaProxyDeleter) {}
+
+DeviceProxy::DeviceProxy(const DeviceProfile& deviceProfile)
+    : mProfile(new alsa_device_profile), mProxy(new alsa_device_proxy, alsaProxyDeleter) {
+    profile_init(mProfile.get(), deviceProfile.direction);
+    mProfile->card = deviceProfile.card;
+    mProfile->device = deviceProfile.device;
+    memset(mProxy.get(), 0, sizeof(alsa_device_proxy));
+}
+
+void DeviceProxy::alsaProxyDeleter(alsa_device_proxy* proxy) {
+    if (proxy != nullptr) {
+        proxy_close(proxy);
+        delete proxy;
+    }
+}
+
 namespace {
 
 using AudioChannelCountToMaskMap = std::map<unsigned int, AudioChannelLayout>;
@@ -261,39 +278,24 @@
     return sampleRates;
 }
 
-DeviceProxy makeDeviceProxy() {
-    DeviceProxy proxy(new alsa_device_proxy, [](alsa_device_proxy* proxy) {
-        if (proxy != nullptr) {
-            proxy_close(proxy);
-            delete proxy;
-        }
-    });
-    memset(proxy.get(), 0, sizeof(alsa_device_proxy));
-    return proxy;
-}
-
 DeviceProxy openProxyForAttachedDevice(const DeviceProfile& deviceProfile,
                                        struct pcm_config* pcmConfig, size_t bufferFrameCount) {
     if (deviceProfile.isExternal) {
         LOG(FATAL) << __func__ << ": called for an external device, address=" << deviceProfile;
     }
-    alsa_device_profile profile;
-    profile_init(&profile, deviceProfile.direction);
-    profile.card = deviceProfile.card;
-    profile.device = deviceProfile.device;
-    if (!profile_fill_builtin_device_info(&profile, pcmConfig, bufferFrameCount)) {
+    DeviceProxy proxy(deviceProfile);
+    if (!profile_fill_builtin_device_info(proxy.getProfile(), pcmConfig, bufferFrameCount)) {
         LOG(FATAL) << __func__ << ": failed to init for built-in device, address=" << deviceProfile;
     }
-    auto proxy = makeDeviceProxy();
-    if (int err = proxy_prepare_from_default_config(proxy.get(), &profile); err != 0) {
+    if (int err = proxy_prepare_from_default_config(proxy.get(), proxy.getProfile()); err != 0) {
         LOG(FATAL) << __func__ << ": fail to prepare for device address=" << deviceProfile
                    << " error=" << err;
-        return nullptr;
+        return DeviceProxy();
     }
     if (int err = proxy_open(proxy.get()); err != 0) {
         LOG(ERROR) << __func__ << ": failed to open device, address=" << deviceProfile
                    << " error=" << err;
-        return nullptr;
+        return DeviceProxy();
     }
     return proxy;
 }
@@ -303,42 +305,36 @@
     if (!deviceProfile.isExternal) {
         LOG(FATAL) << __func__ << ": called for an attached device, address=" << deviceProfile;
     }
-    auto profile = readAlsaDeviceInfo(deviceProfile);
-    if (!profile.has_value()) {
-        LOG(ERROR) << __func__ << ": unable to read device info, device address=" << deviceProfile;
-        return nullptr;
+    auto proxy = readAlsaDeviceInfo(deviceProfile);
+    if (proxy.get() == nullptr) {
+        return proxy;
     }
-    auto proxy = makeDeviceProxy();
-    if (int err = proxy_prepare(proxy.get(), &profile.value(), pcmConfig, requireExactMatch);
+    if (int err = proxy_prepare(proxy.get(), proxy.getProfile(), pcmConfig, requireExactMatch);
         err != 0) {
         LOG(ERROR) << __func__ << ": fail to prepare for device address=" << deviceProfile
                    << " error=" << err;
-        return nullptr;
+        return DeviceProxy();
     }
     if (int err = proxy_open(proxy.get()); err != 0) {
         LOG(ERROR) << __func__ << ": failed to open device, address=" << deviceProfile
                    << " error=" << err;
-        return nullptr;
+        return DeviceProxy();
     }
     return proxy;
 }
 
-std::optional<alsa_device_profile> readAlsaDeviceInfo(const DeviceProfile& deviceProfile) {
-    alsa_device_profile profile;
-    profile_init(&profile, deviceProfile.direction);
-    profile.card = deviceProfile.card;
-    profile.device = deviceProfile.device;
-    if (!profile_read_device_info(&profile)) {
-        LOG(ERROR) << __func__ << ": failed to read device info, card=" << profile.card
-                   << ", device=" << profile.device;
-        return std::nullopt;
+DeviceProxy readAlsaDeviceInfo(const DeviceProfile& deviceProfile) {
+    DeviceProxy proxy(deviceProfile);
+    if (!profile_read_device_info(proxy.getProfile())) {
+        LOG(ERROR) << __func__ << ": unable to read device info, device address=" << deviceProfile;
+        return DeviceProxy();
     }
-    return profile;
+    return proxy;
 }
 
 void resetTransferredFrames(DeviceProxy& proxy, uint64_t frames) {
-    if (proxy != nullptr) {
-        proxy->transferred = frames;
+    if (proxy.get() != nullptr) {
+        proxy.get()->transferred = frames;
     }
 }
 
diff --git a/audio/aidl/default/alsa/Utils.h b/audio/aidl/default/alsa/Utils.h
index 37414b3..980f685 100644
--- a/audio/aidl/default/alsa/Utils.h
+++ b/audio/aidl/default/alsa/Utils.h
@@ -43,8 +43,21 @@
     bool isExternal;
 };
 std::ostream& operator<<(std::ostream& os, const DeviceProfile& device);
-using DeviceProxyDeleter = std::function<void(alsa_device_proxy*)>;
-using DeviceProxy = std::unique_ptr<alsa_device_proxy, DeviceProxyDeleter>;
+
+class DeviceProxy {
+  public:
+    DeviceProxy();  // Constructs a "null" proxy.
+    explicit DeviceProxy(const DeviceProfile& deviceProfile);
+    alsa_device_profile* getProfile() { return mProfile.get(); }
+    alsa_device_proxy* get() { return mProxy.get(); }
+
+  private:
+    static void alsaProxyDeleter(alsa_device_proxy* proxy);
+    using AlsaProxy = std::unique_ptr<alsa_device_proxy, decltype(alsaProxyDeleter)*>;
+
+    std::unique_ptr<alsa_device_profile> mProfile;
+    AlsaProxy mProxy;
+};
 
 ::aidl::android::media::audio::common::AudioChannelLayout getChannelLayoutMaskFromChannelCount(
         unsigned int channelCount, int isInput);
@@ -60,12 +73,11 @@
         const ::aidl::android::media::audio::common::AudioPort& audioPort);
 std::optional<struct pcm_config> getPcmConfig(const StreamContext& context, bool isInput);
 std::vector<int> getSampleRatesFromProfile(const alsa_device_profile* profile);
-DeviceProxy makeDeviceProxy();
 DeviceProxy openProxyForAttachedDevice(const DeviceProfile& deviceProfile,
                                        struct pcm_config* pcmConfig, size_t bufferFrameCount);
 DeviceProxy openProxyForExternalDevice(const DeviceProfile& deviceProfile,
                                        struct pcm_config* pcmConfig, bool requireExactMatch);
-std::optional<alsa_device_profile> readAlsaDeviceInfo(const DeviceProfile& deviceProfile);
+DeviceProxy readAlsaDeviceInfo(const DeviceProfile& deviceProfile);
 void resetTransferredFrames(DeviceProxy& proxy, uint64_t frames);
 
 ::aidl::android::media::audio::common::AudioFormatDescription
diff --git a/audio/aidl/default/bluetooth/ModuleBluetooth.cpp b/audio/aidl/default/bluetooth/ModuleBluetooth.cpp
index bfe7ca0..3c33207 100644
--- a/audio/aidl/default/bluetooth/ModuleBluetooth.cpp
+++ b/audio/aidl/default/bluetooth/ModuleBluetooth.cpp
@@ -18,15 +18,23 @@
 
 #include <android-base/logging.h>
 
+#include "BluetoothAudioSessionControl.h"
 #include "core-impl/ModuleBluetooth.h"
 #include "core-impl/StreamBluetooth.h"
 
 namespace aidl::android::hardware::audio::core {
 
-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::MicrophoneInfo;
+using ::aidl::android::hardware::audio::common::SinkMetadata;
+using ::aidl::android::hardware::audio::common::SourceMetadata;
+using ::aidl::android::hardware::bluetooth::audio::BluetoothAudioSession;
+using ::aidl::android::media::audio::common::AudioDeviceDescription;
+using ::aidl::android::media::audio::common::AudioDeviceType;
+using ::aidl::android::media::audio::common::AudioOffloadInfo;
+using ::aidl::android::media::audio::common::AudioPort;
+using ::aidl::android::media::audio::common::AudioPortExt;
+using ::aidl::android::media::audio::common::MicrophoneInfo;
+using ::android::bluetooth::audio::aidl::BluetoothAudioPortAidl;
+using ::android::bluetooth::audio::aidl::BluetoothAudioPortAidlOut;
 
 ndk::ScopedAStatus ModuleBluetooth::getBluetoothA2dp(
         std::shared_ptr<IBluetoothA2dp>* _aidl_return) {
@@ -80,6 +88,49 @@
                                                     offloadInfo, getBtProfileManagerHandles());
 }
 
+ndk::ScopedAStatus ModuleBluetooth::populateConnectedDevicePort(AudioPort* audioPort) {
+    if (audioPort->ext.getTag() != AudioPortExt::device) {
+        LOG(ERROR) << __func__ << ": not a device port: " << audioPort->toString();
+        return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+    }
+    const auto& devicePort = audioPort->ext.get<AudioPortExt::device>();
+    const auto& description = devicePort.device.type;
+    // Since the configuration of the BT module is static, there is nothing to populate here.
+    // However, this method must return an error when the device can not be connected,
+    // this is determined by the status of BT profiles.
+    if (description.connection == AudioDeviceDescription::CONNECTION_BT_A2DP) {
+        bool isA2dpEnabled = false;
+        if (!!mBluetoothA2dp) {
+            RETURN_STATUS_IF_ERROR(mBluetoothA2dp.getInstance()->isEnabled(&isA2dpEnabled));
+        }
+        return isA2dpEnabled ? ndk::ScopedAStatus::ok()
+                             : ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+    } else if (description.connection == AudioDeviceDescription::CONNECTION_BT_LE) {
+        bool isLeEnabled = false;
+        if (!!mBluetoothLe) {
+            RETURN_STATUS_IF_ERROR(mBluetoothLe.getInstance()->isEnabled(&isLeEnabled));
+        }
+        return isLeEnabled ? ndk::ScopedAStatus::ok()
+                           : ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+    } else if (description.connection == AudioDeviceDescription::CONNECTION_WIRELESS &&
+               description.type == AudioDeviceType::OUT_HEARING_AID) {
+        // Hearing aids can use a number of profiles, thus the only way to check
+        // connectivity is to try to talk to the BT HAL.
+        if (!BluetoothAudioSession::IsAidlAvailable()) {
+            return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+        }
+        std::shared_ptr<BluetoothAudioPortAidl> proxy = std::shared_ptr<BluetoothAudioPortAidl>(
+                std::make_shared<BluetoothAudioPortAidlOut>());
+        if (proxy->registerPort(description)) {
+            proxy->unregisterPort();
+            return ndk::ScopedAStatus::ok();
+        }
+        return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+    }
+    LOG(ERROR) << __func__ << ": unsupported device type: " << audioPort->toString();
+    return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+}
+
 ndk::ScopedAStatus ModuleBluetooth::onMasterMuteChanged(bool) {
     LOG(DEBUG) << __func__ << ": is not supported";
     return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
diff --git a/audio/aidl/default/include/core-impl/Module.h b/audio/aidl/default/include/core-impl/Module.h
index fb3eef2..da94815 100644
--- a/audio/aidl/default/include/core-impl/Module.h
+++ b/audio/aidl/default/include/core-impl/Module.h
@@ -142,7 +142,7 @@
     // ids of device ports created at runtime via 'connectExternalDevice'.
     // Also stores a list of ids of mix ports with dynamic profiles that were populated from
     // the connected port. This list can be empty, thus an int->int multimap can't be used.
-    using ConnectedDevicePorts = std::map<int32_t, std::vector<int32_t>>;
+    using ConnectedDevicePorts = std::map<int32_t, std::set<int32_t>>;
     // Maps port ids and port config ids to patch ids.
     // Multimap because both ports and configs can be used by multiple patches.
     using Patches = std::multimap<int32_t, int32_t>;
@@ -202,6 +202,7 @@
     std::set<int32_t> findConnectedPortConfigIds(int32_t portConfigId);
     ndk::ScopedAStatus findPortIdForNewStream(
             int32_t in_portConfigId, ::aidl::android::media::audio::common::AudioPort** port);
+    std::vector<AudioRoute*> getAudioRoutesForAudioPortImpl(int32_t portId);
     virtual BtProfileHandles getBtProfileManagerHandles();
     internal::Configuration& getConfig();
     const ConnectedDevicePorts& getConnectedDevicePorts() const { return mConnectedDevicePorts; }
@@ -209,6 +210,8 @@
     bool getMasterVolume() const { return mMasterVolume; }
     bool getMicMute() const { return mMicMute; }
     const Patches& getPatches() const { return mPatches; }
+    std::set<int32_t> getRoutableAudioPortIds(int32_t portId,
+                                              std::vector<AudioRoute*>* routes = nullptr);
     const Streams& getStreams() const { return mStreams; }
     Type getType() const { return mType; }
     bool isMmapSupported();
diff --git a/audio/aidl/default/include/core-impl/ModuleBluetooth.h b/audio/aidl/default/include/core-impl/ModuleBluetooth.h
index 68b4e6b..526a809 100644
--- a/audio/aidl/default/include/core-impl/ModuleBluetooth.h
+++ b/audio/aidl/default/include/core-impl/ModuleBluetooth.h
@@ -44,6 +44,8 @@
             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 onMasterMuteChanged(bool mute) override;
     ndk::ScopedAStatus onMasterVolumeChanged(float volume) override;
 
@@ -51,4 +53,4 @@
     ChildInterface<IBluetoothLe> mBluetoothLe;
 };
 
-}  // namespace aidl::android::hardware::audio::core
\ No newline at end of file
+}  // 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 a02655f..88fddec 100644
--- a/audio/aidl/default/include/core-impl/Stream.h
+++ b/audio/aidl/default/include/core-impl/Stream.h
@@ -223,6 +223,7 @@
         : mContext(context),
           mDriver(driver),
           mTransientStateDelayMs(context->getTransientStateDelayMs()) {}
+    pid_t getTid() const;
     std::string init() override;
     void populateReply(StreamDescriptor::Reply* reply, bool isConnected) const;
     void populateReplyWrongState(StreamDescriptor::Reply* reply,
diff --git a/audio/aidl/default/include/effect-impl/EffectWorker.h b/audio/aidl/default/include/effect-impl/EffectWorker.h
deleted file mode 100644
index 421429a..0000000
--- a/audio/aidl/default/include/effect-impl/EffectWorker.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * 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 <algorithm>
-#include <memory>
-#include <mutex>
-#include <string>
-
-#include "EffectContext.h"
-#include "EffectThread.h"
-
-namespace aidl::android::hardware::audio::effect {
-
-std::string toString(RetCode& code);
-
-class EffectWorker : public EffectThread {
-  public:
-    // set effect context for worker, suppose to only happen once here
-    void setContext(std::shared_ptr<EffectContext> context) {
-        std::call_once(mOnceFlag, [&]() { mContext = context; });
-    };
-
-    // handle FMQ and call effect implemented virtual function
-    void process() override {
-        RETURN_VALUE_IF(!mContext, void(), "nullContext");
-        std::shared_ptr<EffectContext::StatusMQ> statusMQ = mContext->getStatusFmq();
-        std::shared_ptr<EffectContext::DataMQ> inputMQ = mContext->getInputDataFmq();
-        std::shared_ptr<EffectContext::DataMQ> outputMQ = mContext->getOutputDataFmq();
-
-        // Only this worker will read from input data MQ and write to output data MQ.
-        auto readSamples = inputMQ->availableToRead(), writeSamples = outputMQ->availableToWrite();
-        if (readSamples && writeSamples) {
-            auto processSamples = std::min(readSamples, writeSamples);
-            LOG(VERBOSE) << __func__ << " available to read " << readSamples
-                         << " available to write " << writeSamples << " process " << processSamples;
-
-            auto buffer = mContext->getWorkBuffer();
-            inputMQ->read(buffer, processSamples);
-
-            IEffect::Status status = effectProcessImpl(buffer, buffer, processSamples);
-            outputMQ->write(buffer, status.fmqProduced);
-            statusMQ->writeBlocking(&status, 1);
-            LOG(VERBOSE) << __func__ << " done processing, effect consumed " << status.fmqConsumed
-                         << " produced " << status.fmqProduced;
-        } else {
-            // TODO: maybe add some sleep here to avoid busy waiting
-        }
-    }
-
-    // must implement by each effect implementation
-    // TODO: consider if this interface need adjustment to handle in-place processing
-    virtual IEffect::Status effectProcessImpl(float* in, float* out, int samples) = 0;
-
-  private:
-    // make sure the context only set once.
-    std::once_flag mOnceFlag;
-    std::shared_ptr<EffectContext> mContext;
-};
-
-}  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/r_submix/ModuleRemoteSubmix.cpp b/audio/aidl/default/r_submix/ModuleRemoteSubmix.cpp
index adea877..f8c775f 100644
--- a/audio/aidl/default/r_submix/ModuleRemoteSubmix.cpp
+++ b/audio/aidl/default/r_submix/ModuleRemoteSubmix.cpp
@@ -59,23 +59,22 @@
 
 ndk::ScopedAStatus ModuleRemoteSubmix::populateConnectedDevicePort(AudioPort* audioPort) {
     // Find the corresponding mix port and copy its profiles.
-    std::vector<AudioRoute> routes;
     // At this moment, the port has the same ID as the template port, see connectExternalDevice.
-    RETURN_STATUS_IF_ERROR(getAudioRoutesForAudioPort(audioPort->id, &routes));
+    std::vector<AudioRoute*> routes = getAudioRoutesForAudioPortImpl(audioPort->id);
     if (routes.empty()) {
         LOG(ERROR) << __func__ << ": no routes found for the port " << audioPort->toString();
         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
     }
     const auto& route = *routes.begin();
     AudioPort mixPort;
-    if (route.sinkPortId == audioPort->id) {
-        if (route.sourcePortIds.empty()) {
-            LOG(ERROR) << __func__ << ": invalid route " << route.toString();
+    if (route->sinkPortId == audioPort->id) {
+        if (route->sourcePortIds.empty()) {
+            LOG(ERROR) << __func__ << ": invalid route " << route->toString();
             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
         }
-        RETURN_STATUS_IF_ERROR(getAudioPort(*route.sourcePortIds.begin(), &mixPort));
+        RETURN_STATUS_IF_ERROR(getAudioPort(*route->sourcePortIds.begin(), &mixPort));
     } else {
-        RETURN_STATUS_IF_ERROR(getAudioPort(route.sinkPortId, &mixPort));
+        RETURN_STATUS_IF_ERROR(getAudioPort(route->sinkPortId, &mixPort));
     }
     audioPort->profiles = mixPort.profiles;
     return ndk::ScopedAStatus::ok();
diff --git a/audio/aidl/default/r_submix/StreamRemoteSubmix.cpp b/audio/aidl/default/r_submix/StreamRemoteSubmix.cpp
index 3134b86..9c9c08b 100644
--- a/audio/aidl/default/r_submix/StreamRemoteSubmix.cpp
+++ b/audio/aidl/default/r_submix/StreamRemoteSubmix.cpp
@@ -179,7 +179,7 @@
         LOG(ERROR) << __func__ << ": transfer without a pipe!";
         return ::android::UNEXPECTED_NULL;
     }
-
+    mCurrentRoute->exitStandby(mIsInput);
     return (mIsInput ? inRead(buffer, frameCount, actualFrameCount)
                      : outWrite(buffer, frameCount, actualFrameCount));
 }
@@ -190,17 +190,14 @@
         return ::android::NO_INIT;
     }
     const ssize_t framesInPipe = source->availableToRead();
-    if (framesInPipe < 0) {
-        return ::android::INVALID_OPERATION;
+    if (framesInPipe <= 0) {
+        // No need to update the position frames
+        return ::android::OK;
     }
     if (mIsInput) {
         position->frames += framesInPipe;
-    } else {
-        if (position->frames > framesInPipe) {
-            position->frames -= framesInPipe;
-        } else {
-            position->frames = 0;
-        }
+    } else if (position->frames >= framesInPipe) {
+        position->frames -= framesInPipe;
     }
     return ::android::OK;
 }
@@ -280,18 +277,14 @@
                                                size_t* actualFrameCount) {
     // about to read from audio source
     sp<MonoPipeReader> source = mCurrentRoute->getSource();
-    if (source == nullptr || source->availableToRead() == 0) {
-        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;
-            }
+    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(INFO) << __func__ << ": no data to read yet, providing empty data";
+            LOG(ERROR) << __func__ << ": Read errors " << readErrorCount;
         }
         const size_t delayUs = static_cast<size_t>(
                 std::roundf(frameCount * MICROS_PER_SECOND / mStreamConfig.sampleRate));
@@ -306,9 +299,10 @@
     const size_t delayUs = static_cast<size_t>(std::roundf(kReadAttemptSleepUs));
     char* buff = (char*)buffer;
     size_t remainingFrames = frameCount;
+    int availableToRead = source->availableToRead();
 
-    while ((remainingFrames > 0) && (attempts < kMaxReadFailureAttempts)) {
-        LOG(VERBOSE) << __func__ << ": frames available to read " << source->availableToRead();
+    while ((remainingFrames > 0) && (availableToRead > 0) && (attempts < kMaxReadFailureAttempts)) {
+        LOG(VERBOSE) << __func__ << ": frames available to read " << availableToRead;
 
         ssize_t framesRead = source->read(buff, remainingFrames);
 
@@ -317,6 +311,7 @@
         if (framesRead > 0) {
             remainingFrames -= framesRead;
             buff += framesRead * mStreamConfig.frameSize;
+            availableToRead -= framesRead;
             LOG(VERBOSE) << __func__ << ": (attempts = " << attempts << ") got " << framesRead
                          << " frames, remaining=" << remainingFrames;
         } else {
diff --git a/audio/aidl/default/usb/StreamUsb.cpp b/audio/aidl/default/usb/StreamUsb.cpp
index b60b4fd..9b10432 100644
--- a/audio/aidl/default/usb/StreamUsb.cpp
+++ b/audio/aidl/default/usb/StreamUsb.cpp
@@ -52,7 +52,7 @@
         }
         connectedDeviceProfiles.push_back(*profile);
     }
-    RETURN_STATUS_IF_ERROR(setConnectedDevices(connectedDevices));
+    RETURN_STATUS_IF_ERROR(StreamCommonImpl::setConnectedDevices(connectedDevices));
     std::lock_guard guard(mLock);
     mConnectedDeviceProfiles = std::move(connectedDeviceProfiles);
     mConnectedDevicesUpdated.store(true, std::memory_order_release);
diff --git a/audio/aidl/vts/Android.bp b/audio/aidl/vts/Android.bp
index f7cf4ce..a2f0260 100644
--- a/audio/aidl/vts/Android.bp
+++ b/audio/aidl/vts/Android.bp
@@ -26,7 +26,10 @@
         "libaudioaidlcommon",
         "libaidlcommonsupport",
     ],
-    header_libs: ["libaudioaidl_headers"],
+    header_libs: [
+        "libaudioaidl_headers",
+        "libexpectedutils_headers",
+    ],
     cflags: [
         "-Wall",
         "-Wextra",
diff --git a/audio/aidl/vts/EffectHelper.h b/audio/aidl/vts/EffectHelper.h
index 685d07d..2c8edf2 100644
--- a/audio/aidl/vts/EffectHelper.h
+++ b/audio/aidl/vts/EffectHelper.h
@@ -250,11 +250,11 @@
                    maxLimit = std::numeric_limits<S>::max();
         if (s.size()) {
             const auto min = *s.begin(), max = *s.rbegin();
-            s.insert(min + (max - min) / 2);
-            if (min != minLimit) {
+            s.insert((min & max) + ((min ^ max) >> 1));
+            if (min > minLimit + 1) {
                 s.insert(min - 1);
             }
-            if (max != maxLimit) {
+            if (max < maxLimit - 1) {
                 s.insert(max + 1);
             }
         }
diff --git a/audio/aidl/vts/ModuleConfig.cpp b/audio/aidl/vts/ModuleConfig.cpp
index 7213034..8f19547 100644
--- a/audio/aidl/vts/ModuleConfig.cpp
+++ b/audio/aidl/vts/ModuleConfig.cpp
@@ -21,6 +21,7 @@
 #include <aidl/android/media/audio/common/AudioInputFlags.h>
 #include <aidl/android/media/audio/common/AudioIoFlags.h>
 #include <aidl/android/media/audio/common/AudioOutputFlags.h>
+#include <error/expected_utils.h>
 
 #include "ModuleConfig.h"
 
@@ -66,15 +67,36 @@
     return {};
 }
 
+std::vector<aidl::android::media::audio::common::AudioPort>
+ModuleConfig::getAudioPortsForDeviceTypes(const std::vector<AudioDeviceType>& deviceTypes,
+                                          const std::string& connection) {
+    return getAudioPortsForDeviceTypes(mPorts, deviceTypes, connection);
+}
+
 // static
 std::vector<aidl::android::media::audio::common::AudioPort> ModuleConfig::getBuiltInMicPorts(
         const std::vector<aidl::android::media::audio::common::AudioPort>& ports) {
+    return getAudioPortsForDeviceTypes(
+            ports, std::vector<AudioDeviceType>{AudioDeviceType::IN_MICROPHONE,
+                                                AudioDeviceType::IN_MICROPHONE_BACK});
+}
+
+std::vector<aidl::android::media::audio::common::AudioPort>
+ModuleConfig::getAudioPortsForDeviceTypes(
+        const std::vector<aidl::android::media::audio::common::AudioPort>& ports,
+        const std::vector<AudioDeviceType>& deviceTypes, const std::string& connection) {
     std::vector<AudioPort> result;
-    std::copy_if(ports.begin(), ports.end(), std::back_inserter(result), [](const auto& port) {
-        const auto type = port.ext.template get<AudioPortExt::Tag::device>().device.type;
-        return type.connection.empty() && (type.type == AudioDeviceType::IN_MICROPHONE ||
-                                           type.type == AudioDeviceType::IN_MICROPHONE_BACK);
-    });
+    for (const auto& port : ports) {
+        if (port.ext.getTag() != AudioPortExt::Tag::device) continue;
+        const auto type = port.ext.get<AudioPortExt::Tag::device>().device.type;
+        if (type.connection == connection) {
+            for (auto deviceType : deviceTypes) {
+                if (type.type == deviceType) {
+                    result.push_back(port);
+                }
+            }
+        }
+    }
     return result;
 }
 
@@ -119,6 +141,31 @@
     return result;
 }
 
+std::vector<AudioPort> ModuleConfig::getConnectedExternalDevicePorts() const {
+    std::vector<AudioPort> result;
+    std::copy_if(mPorts.begin(), mPorts.end(), std::back_inserter(result), [&](const auto& port) {
+        return mConnectedExternalSinkDevicePorts.count(port.id) != 0 ||
+               mConnectedExternalSourceDevicePorts.count(port.id) != 0;
+    });
+    return result;
+}
+
+std::set<int32_t> ModuleConfig::getConnectedSinkDevicePorts() const {
+    std::set<int32_t> result;
+    result.insert(mAttachedSinkDevicePorts.begin(), mAttachedSinkDevicePorts.end());
+    result.insert(mConnectedExternalSinkDevicePorts.begin(),
+                  mConnectedExternalSinkDevicePorts.end());
+    return result;
+}
+
+std::set<int32_t> ModuleConfig::getConnectedSourceDevicePorts() const {
+    std::set<int32_t> result;
+    result.insert(mAttachedSourceDevicePorts.begin(), mAttachedSourceDevicePorts.end());
+    result.insert(mConnectedExternalSourceDevicePorts.begin(),
+                  mConnectedExternalSourceDevicePorts.end());
+    return result;
+}
+
 std::vector<AudioPort> ModuleConfig::getExternalDevicePorts() const {
     std::vector<AudioPort> result;
     std::copy_if(mPorts.begin(), mPorts.end(), std::back_inserter(result),
@@ -126,76 +173,77 @@
     return result;
 }
 
-std::vector<AudioPort> ModuleConfig::getInputMixPorts(bool attachedOnly) const {
+std::vector<AudioPort> ModuleConfig::getInputMixPorts(bool connectedOnly) const {
     std::vector<AudioPort> result;
     std::copy_if(mPorts.begin(), mPorts.end(), std::back_inserter(result), [&](const auto& port) {
         return port.ext.getTag() == AudioPortExt::Tag::mix &&
                port.flags.getTag() == AudioIoFlags::Tag::input &&
-               (!attachedOnly || !getAttachedSourceDevicesPortsForMixPort(port).empty());
+               (!connectedOnly || !getConnectedSourceDevicesPortsForMixPort(port).empty());
     });
     return result;
 }
 
-std::vector<AudioPort> ModuleConfig::getOutputMixPorts(bool attachedOnly) const {
+std::vector<AudioPort> ModuleConfig::getOutputMixPorts(bool connectedOnly) const {
     std::vector<AudioPort> result;
     std::copy_if(mPorts.begin(), mPorts.end(), std::back_inserter(result), [&](const auto& port) {
         return port.ext.getTag() == AudioPortExt::Tag::mix &&
                port.flags.getTag() == AudioIoFlags::Tag::output &&
-               (!attachedOnly || !getAttachedSinkDevicesPortsForMixPort(port).empty());
+               (!connectedOnly || !getConnectedSinkDevicesPortsForMixPort(port).empty());
     });
     return result;
 }
 
-std::vector<AudioPort> ModuleConfig::getNonBlockingMixPorts(bool attachedOnly,
+std::vector<AudioPort> ModuleConfig::getNonBlockingMixPorts(bool connectedOnly,
                                                             bool singlePort) const {
-    return findMixPorts(false /*isInput*/, attachedOnly, singlePort, [&](const AudioPort& port) {
+    return findMixPorts(false /*isInput*/, connectedOnly, singlePort, [&](const AudioPort& port) {
         return isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
                                     AudioOutputFlags::NON_BLOCKING);
     });
 }
 
-std::vector<AudioPort> ModuleConfig::getOffloadMixPorts(bool attachedOnly, bool singlePort) const {
-    return findMixPorts(false /*isInput*/, attachedOnly, singlePort, [&](const AudioPort& port) {
+std::vector<AudioPort> ModuleConfig::getOffloadMixPorts(bool connectedOnly, bool singlePort) const {
+    return findMixPorts(false /*isInput*/, connectedOnly, singlePort, [&](const AudioPort& port) {
         return isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
                                     AudioOutputFlags::COMPRESS_OFFLOAD);
     });
 }
 
-std::vector<AudioPort> ModuleConfig::getPrimaryMixPorts(bool attachedOnly, bool singlePort) const {
-    return findMixPorts(false /*isInput*/, attachedOnly, singlePort, [&](const AudioPort& port) {
+std::vector<AudioPort> ModuleConfig::getPrimaryMixPorts(bool connectedOnly, bool singlePort) const {
+    return findMixPorts(false /*isInput*/, connectedOnly, singlePort, [&](const AudioPort& port) {
         return isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
                                     AudioOutputFlags::PRIMARY);
     });
 }
 
-std::vector<AudioPort> ModuleConfig::getMmapOutMixPorts(bool attachedOnly, bool singlePort) const {
-    return findMixPorts(false /*isInput*/, attachedOnly, singlePort, [&](const AudioPort& port) {
+std::vector<AudioPort> ModuleConfig::getMmapOutMixPorts(bool connectedOnly, bool singlePort) const {
+    return findMixPorts(false /*isInput*/, connectedOnly, singlePort, [&](const AudioPort& port) {
         return isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
                                     AudioOutputFlags::MMAP_NOIRQ);
     });
 }
 
-std::vector<AudioPort> ModuleConfig::getMmapInMixPorts(bool attachedOnly, bool singlePort) const {
-    return findMixPorts(true /*isInput*/, attachedOnly, singlePort, [&](const AudioPort& port) {
+std::vector<AudioPort> ModuleConfig::getMmapInMixPorts(bool connectedOnly, bool singlePort) const {
+    return findMixPorts(true /*isInput*/, connectedOnly, singlePort, [&](const AudioPort& port) {
         return isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::input>(),
                                     AudioInputFlags::MMAP_NOIRQ);
     });
 }
 
-std::vector<AudioPort> ModuleConfig::getAttachedDevicesPortsForMixPort(
+std::vector<AudioPort> ModuleConfig::getConnectedDevicesPortsForMixPort(
         bool isInput, const AudioPortConfig& mixPortConfig) const {
     const auto mixPortIt = findById<AudioPort>(mPorts, mixPortConfig.portId);
     if (mixPortIt != mPorts.end()) {
-        return getAttachedDevicesPortsForMixPort(isInput, *mixPortIt);
+        return getConnectedDevicesPortsForMixPort(isInput, *mixPortIt);
     }
     return {};
 }
 
-std::vector<AudioPort> ModuleConfig::getAttachedSinkDevicesPortsForMixPort(
+std::vector<AudioPort> ModuleConfig::getConnectedSinkDevicesPortsForMixPort(
         const AudioPort& mixPort) const {
     std::vector<AudioPort> result;
+    std::set<int32_t> connectedSinkDevicePorts = getConnectedSinkDevicePorts();
     for (const auto& route : mRoutes) {
-        if (mAttachedSinkDevicePorts.count(route.sinkPortId) != 0 &&
+        if ((connectedSinkDevicePorts.count(route.sinkPortId) != 0) &&
             std::find(route.sourcePortIds.begin(), route.sourcePortIds.end(), mixPort.id) !=
                     route.sourcePortIds.end()) {
             const auto devicePortIt = findById<AudioPort>(mPorts, route.sinkPortId);
@@ -205,13 +253,14 @@
     return result;
 }
 
-std::vector<AudioPort> ModuleConfig::getAttachedSourceDevicesPortsForMixPort(
+std::vector<AudioPort> ModuleConfig::getConnectedSourceDevicesPortsForMixPort(
         const AudioPort& mixPort) const {
     std::vector<AudioPort> result;
+    std::set<int32_t> connectedSourceDevicePorts = getConnectedSourceDevicePorts();
     for (const auto& route : mRoutes) {
         if (route.sinkPortId == mixPort.id) {
             for (const auto srcId : route.sourcePortIds) {
-                if (mAttachedSourceDevicePorts.count(srcId) != 0) {
+                if (connectedSourceDevicePorts.count(srcId) != 0) {
                     const auto devicePortIt = findById<AudioPort>(mPorts, srcId);
                     if (devicePortIt != mPorts.end()) result.push_back(*devicePortIt);
                 }
@@ -221,9 +270,10 @@
     return result;
 }
 
-std::optional<AudioPort> ModuleConfig::getSourceMixPortForAttachedDevice() const {
+std::optional<AudioPort> ModuleConfig::getSourceMixPortForConnectedDevice() const {
+    std::set<int32_t> connectedSinkDevicePorts = getConnectedSinkDevicePorts();
     for (const auto& route : mRoutes) {
-        if (mAttachedSinkDevicePorts.count(route.sinkPortId) != 0) {
+        if (connectedSinkDevicePorts.count(route.sinkPortId) != 0) {
             const auto mixPortIt = findById<AudioPort>(mPorts, route.sourcePortIds[0]);
             if (mixPortIt != mPorts.end()) return *mixPortIt;
         }
@@ -231,9 +281,25 @@
     return {};
 }
 
+std::vector<AudioPort> ModuleConfig::getRoutableMixPortsForDevicePort(const AudioPort& port) const {
+    std::set<int32_t> portIds;
+    for (const auto& route : mRoutes) {
+        if (port.id == route.sinkPortId) {
+            portIds.insert(route.sourcePortIds.begin(), route.sourcePortIds.end());
+        } else if (auto it = std::find(route.sourcePortIds.begin(), route.sourcePortIds.end(),
+                                       port.id);
+                   it != route.sourcePortIds.end()) {
+            portIds.insert(route.sinkPortId);
+        }
+    }
+    const bool isInput = port.flags.getTag() == AudioIoFlags::input;
+    return findMixPorts(isInput, false /*connectedOnly*/, false /*singlePort*/,
+                        [&portIds](const AudioPort& p) { return portIds.count(p.id) > 0; });
+}
+
 std::optional<ModuleConfig::SrcSinkPair> ModuleConfig::getNonRoutableSrcSinkPair(
         bool isInput) const {
-    const auto mixPorts = getMixPorts(isInput, false /*attachedOnly*/);
+    const auto mixPorts = getMixPorts(isInput, false /*connectedOnly*/);
     std::set<std::pair<int32_t, int32_t>> allowedRoutes;
     for (const auto& route : mRoutes) {
         for (const auto srcPortId : route.sourcePortIds) {
@@ -243,7 +309,8 @@
     auto make_pair = [isInput](auto& device, auto& mix) {
         return isInput ? std::make_pair(device, mix) : std::make_pair(mix, device);
     };
-    for (const auto portId : isInput ? mAttachedSourceDevicePorts : mAttachedSinkDevicePorts) {
+    for (const auto portId :
+         isInput ? getConnectedSourceDevicePorts() : getConnectedSinkDevicePorts()) {
         const auto devicePortIt = findById<AudioPort>(mPorts, portId);
         if (devicePortIt == mPorts.end()) continue;
         auto devicePortConfig = getSingleConfigForDevicePort(*devicePortIt);
@@ -262,10 +329,11 @@
 
 std::optional<ModuleConfig::SrcSinkPair> ModuleConfig::getRoutableSrcSinkPair(bool isInput) const {
     if (isInput) {
+        std::set<int32_t> connectedSourceDevicePorts = getConnectedSourceDevicePorts();
         for (const auto& route : mRoutes) {
             auto srcPortIdIt = std::find_if(
                     route.sourcePortIds.begin(), route.sourcePortIds.end(),
-                    [&](const auto& portId) { return mAttachedSourceDevicePorts.count(portId); });
+                    [&](const auto& portId) { return connectedSourceDevicePorts.count(portId); });
             if (srcPortIdIt == route.sourcePortIds.end()) continue;
             const auto devicePortIt = findById<AudioPort>(mPorts, *srcPortIdIt);
             const auto mixPortIt = findById<AudioPort>(mPorts, route.sinkPortId);
@@ -276,8 +344,9 @@
             return std::make_pair(devicePortConfig, mixPortConfig.value());
         }
     } else {
+        std::set<int32_t> connectedSinkDevicePorts = getConnectedSinkDevicePorts();
         for (const auto& route : mRoutes) {
-            if (mAttachedSinkDevicePorts.count(route.sinkPortId) == 0) continue;
+            if (connectedSinkDevicePorts.count(route.sinkPortId) == 0) continue;
             const auto mixPortIt = findById<AudioPort>(mPorts, route.sourcePortIds[0]);
             const auto devicePortIt = findById<AudioPort>(mPorts, route.sinkPortId);
             if (devicePortIt == mPorts.end() || mixPortIt == mPorts.end()) continue;
@@ -293,11 +362,12 @@
 std::vector<ModuleConfig::SrcSinkGroup> ModuleConfig::getRoutableSrcSinkGroups(bool isInput) const {
     std::vector<SrcSinkGroup> result;
     if (isInput) {
+        std::set<int32_t> connectedSourceDevicePorts = getConnectedSourceDevicePorts();
         for (const auto& route : mRoutes) {
             std::vector<int32_t> srcPortIds;
             std::copy_if(route.sourcePortIds.begin(), route.sourcePortIds.end(),
                          std::back_inserter(srcPortIds), [&](const auto& portId) {
-                             return mAttachedSourceDevicePorts.count(portId);
+                             return connectedSourceDevicePorts.count(portId);
                          });
             if (srcPortIds.empty()) continue;
             const auto mixPortIt = findById<AudioPort>(mPorts, route.sinkPortId);
@@ -317,8 +387,9 @@
             }
         }
     } else {
+        std::set<int32_t> connectedSinkDevicePorts = getConnectedSinkDevicePorts();
         for (const auto& route : mRoutes) {
-            if (mAttachedSinkDevicePorts.count(route.sinkPortId) == 0) continue;
+            if (connectedSinkDevicePorts.count(route.sinkPortId) == 0) continue;
             const auto devicePortIt = findById<AudioPort>(mPorts, route.sinkPortId);
             if (devicePortIt == mPorts.end()) continue;
             auto devicePortConfig = getSingleConfigForDevicePort(*devicePortIt);
@@ -352,6 +423,8 @@
     result.append(android::internal::ToString(mAttachedSourceDevicePorts));
     result.append("\nExternal device ports: ");
     result.append(android::internal::ToString(mExternalDevicePorts));
+    result.append("\nConnected external device ports: ");
+    result.append(android::internal::ToString(getConnectedExternalDevicePorts()));
     result.append("\nRoutes: ");
     result.append(android::internal::ToString(mRoutes));
     return result;
@@ -384,10 +457,10 @@
 }
 
 std::vector<AudioPort> ModuleConfig::findMixPorts(
-        bool isInput, bool attachedOnly, bool singlePort,
+        bool isInput, bool connectedOnly, bool singlePort,
         const std::function<bool(const AudioPort&)>& pred) const {
     std::vector<AudioPort> result;
-    const auto mixPorts = getMixPorts(isInput, attachedOnly);
+    const auto mixPorts = getMixPorts(isInput, connectedOnly);
     for (auto mixPortIt = mixPorts.begin(); mixPortIt != mixPorts.end();) {
         mixPortIt = std::find_if(mixPortIt, mixPorts.end(), pred);
         if (mixPortIt == mixPorts.end()) break;
@@ -401,7 +474,7 @@
         const std::vector<AudioPort>& ports, bool isInput, bool singleProfile) const {
     std::vector<AudioPortConfig> result;
     for (const auto& mixPort : ports) {
-        if (getAttachedDevicesPortsForMixPort(isInput, mixPort).empty()) {
+        if (getConnectedDevicesPortsForMixPort(isInput, mixPort).empty()) {
             continue;
         }
         for (const auto& profile : mixPort.profiles) {
@@ -443,10 +516,40 @@
     return result;
 }
 
+ndk::ScopedAStatus ModuleConfig::onExternalDeviceConnected(IModule* module, const AudioPort& port) {
+    RETURN_STATUS_IF_ERROR(module->getAudioPorts(&mPorts));
+    RETURN_STATUS_IF_ERROR(module->getAudioRoutes(&mRoutes));
+
+    // Validate port is present in module
+    if (std::find(mPorts.begin(), mPorts.end(), port) == mPorts.end()) {
+        return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+    }
+
+    if (port.flags.getTag() == aidl::android::media::audio::common::AudioIoFlags::Tag::input) {
+        mConnectedExternalSourceDevicePorts.insert(port.id);
+    } else {
+        mConnectedExternalSinkDevicePorts.insert(port.id);
+    }
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleConfig::onExternalDeviceDisconnected(IModule* module,
+                                                              const AudioPort& port) {
+    RETURN_STATUS_IF_ERROR(module->getAudioPorts(&mPorts));
+    RETURN_STATUS_IF_ERROR(module->getAudioRoutes(&mRoutes));
+
+    if (port.flags.getTag() == aidl::android::media::audio::common::AudioIoFlags::Tag::input) {
+        mConnectedExternalSourceDevicePorts.erase(port.id);
+    } else {
+        mConnectedExternalSinkDevicePorts.erase(port.id);
+    }
+    return ndk::ScopedAStatus::ok();
+}
+
 bool ModuleConfig::isMmapSupported() const {
     const std::vector<AudioPort> mmapOutMixPorts =
-            getMmapOutMixPorts(false /*attachedOnly*/, false /*singlePort*/);
+            getMmapOutMixPorts(false /*connectedOnly*/, false /*singlePort*/);
     const std::vector<AudioPort> mmapInMixPorts =
-            getMmapInMixPorts(false /*attachedOnly*/, false /*singlePort*/);
+            getMmapInMixPorts(false /*connectedOnly*/, false /*singlePort*/);
     return !mmapOutMixPorts.empty() || !mmapInMixPorts.empty();
 }
diff --git a/audio/aidl/vts/ModuleConfig.h b/audio/aidl/vts/ModuleConfig.h
index 6a22075..b89adc0 100644
--- a/audio/aidl/vts/ModuleConfig.h
+++ b/audio/aidl/vts/ModuleConfig.h
@@ -37,6 +37,14 @@
     static std::optional<aidl::android::media::audio::common::AudioOffloadInfo>
     generateOffloadInfoIfNeeded(
             const aidl::android::media::audio::common::AudioPortConfig& portConfig);
+
+    std::vector<aidl::android::media::audio::common::AudioPort> getAudioPortsForDeviceTypes(
+            const std::vector<aidl::android::media::audio::common::AudioDeviceType>& deviceTypes,
+            const std::string& connection = "");
+    static std::vector<aidl::android::media::audio::common::AudioPort> getAudioPortsForDeviceTypes(
+            const std::vector<aidl::android::media::audio::common::AudioPort>& ports,
+            const std::vector<aidl::android::media::audio::common::AudioDeviceType>& deviceTypes,
+            const std::string& connection = "");
     static std::vector<aidl::android::media::audio::common::AudioPort> getBuiltInMicPorts(
             const std::vector<aidl::android::media::audio::common::AudioPort>& ports);
 
@@ -45,45 +53,58 @@
     std::string getError() const { return mStatus.getMessage(); }
 
     std::vector<aidl::android::media::audio::common::AudioPort> getAttachedDevicePorts() const;
+    std::vector<aidl::android::media::audio::common::AudioPort> getConnectedExternalDevicePorts()
+            const;
+    std::set<int32_t> getConnectedSinkDevicePorts() const;
+    std::set<int32_t> getConnectedSourceDevicePorts() const;
     std::vector<aidl::android::media::audio::common::AudioPort> getAttachedMicrophonePorts() const {
         return getBuiltInMicPorts(getAttachedDevicePorts());
     }
     std::vector<aidl::android::media::audio::common::AudioPort> getExternalDevicePorts() const;
     std::vector<aidl::android::media::audio::common::AudioPort> getInputMixPorts(
-            bool attachedOnly) const;
+            bool connectedOnly /*Permanently attached and connected external devices*/) const;
     std::vector<aidl::android::media::audio::common::AudioPort> getOutputMixPorts(
-            bool attachedOnly) const;
+            bool connectedOnly /*Permanently attached and connected external devices*/) const;
     std::vector<aidl::android::media::audio::common::AudioPort> getMixPorts(
-            bool isInput, bool attachedOnly) const {
-        return isInput ? getInputMixPorts(attachedOnly) : getOutputMixPorts(attachedOnly);
+            bool isInput,
+            bool connectedOnly /*Permanently attached and connected external devices*/) const {
+        return isInput ? getInputMixPorts(connectedOnly) : getOutputMixPorts(connectedOnly);
     }
     std::vector<aidl::android::media::audio::common::AudioPort> getNonBlockingMixPorts(
-            bool attachedOnly, bool singlePort) const;
+            bool connectedOnly /*Permanently attached and connected external devices*/,
+            bool singlePort) const;
     std::vector<aidl::android::media::audio::common::AudioPort> getOffloadMixPorts(
-            bool attachedOnly, bool singlePort) const;
+            bool connectedOnly /*Permanently attached and connected external devices*/,
+            bool singlePort) const;
     std::vector<aidl::android::media::audio::common::AudioPort> getPrimaryMixPorts(
-            bool attachedOnly, bool singlePort) const;
+            bool connectedOnly /*Permanently attached and connected external devices*/,
+            bool singlePort) const;
     std::vector<aidl::android::media::audio::common::AudioPort> getMmapOutMixPorts(
-            bool attachedOnly, bool singlePort) const;
+            bool connectedOnly /*Permanently attached and connected external devices*/,
+            bool singlePort) const;
     std::vector<aidl::android::media::audio::common::AudioPort> getMmapInMixPorts(
-            bool attachedOnly, bool singlePort) const;
+            bool connectedOnly /*Permanently attached and connected external devices*/,
+            bool singlePort) const;
 
-    std::vector<aidl::android::media::audio::common::AudioPort> getAttachedDevicesPortsForMixPort(
+    std::vector<aidl::android::media::audio::common::AudioPort> getConnectedDevicesPortsForMixPort(
             bool isInput, const aidl::android::media::audio::common::AudioPort& mixPort) const {
-        return isInput ? getAttachedSourceDevicesPortsForMixPort(mixPort)
-                       : getAttachedSinkDevicesPortsForMixPort(mixPort);
+        return isInput ? getConnectedSourceDevicesPortsForMixPort(mixPort)
+                       : getConnectedSinkDevicesPortsForMixPort(mixPort);
     }
-    std::vector<aidl::android::media::audio::common::AudioPort> getAttachedDevicesPortsForMixPort(
+    std::vector<aidl::android::media::audio::common::AudioPort> getConnectedDevicesPortsForMixPort(
             bool isInput,
             const aidl::android::media::audio::common::AudioPortConfig& mixPortConfig) const;
     std::vector<aidl::android::media::audio::common::AudioPort>
-    getAttachedSinkDevicesPortsForMixPort(
+    getConnectedSinkDevicesPortsForMixPort(
             const aidl::android::media::audio::common::AudioPort& mixPort) const;
     std::vector<aidl::android::media::audio::common::AudioPort>
-    getAttachedSourceDevicesPortsForMixPort(
+    getConnectedSourceDevicesPortsForMixPort(
             const aidl::android::media::audio::common::AudioPort& mixPort) const;
     std::optional<aidl::android::media::audio::common::AudioPort>
-    getSourceMixPortForAttachedDevice() const;
+    getSourceMixPortForConnectedDevice() const;
+
+    std::vector<aidl::android::media::audio::common::AudioPort> getRoutableMixPortsForDevicePort(
+            const aidl::android::media::audio::common::AudioPort& port) const;
 
     std::optional<SrcSinkPair> getNonRoutableSrcSinkPair(bool isInput) const;
     std::optional<SrcSinkPair> getRoutableSrcSinkPair(bool isInput) const;
@@ -96,15 +117,15 @@
     std::vector<aidl::android::media::audio::common::AudioPortConfig> getPortConfigsForMixPorts()
             const {
         auto inputs =
-                generateAudioMixPortConfigs(getInputMixPorts(false /*attachedOnly*/), true, false);
-        auto outputs = generateAudioMixPortConfigs(getOutputMixPorts(false /*attachedOnly*/), false,
-                                                   false);
+                generateAudioMixPortConfigs(getInputMixPorts(false /*connectedOnly*/), true, false);
+        auto outputs = generateAudioMixPortConfigs(getOutputMixPorts(false /*connectedOnly*/),
+                                                   false, false);
         inputs.insert(inputs.end(), outputs.begin(), outputs.end());
         return inputs;
     }
     std::vector<aidl::android::media::audio::common::AudioPortConfig> getPortConfigsForMixPorts(
             bool isInput) const {
-        return generateAudioMixPortConfigs(getMixPorts(isInput, false /*attachedOnly*/), isInput,
+        return generateAudioMixPortConfigs(getMixPorts(isInput, false /*connectedOnly*/), isInput,
                                            false);
     }
     std::vector<aidl::android::media::audio::common::AudioPortConfig> getPortConfigsForMixPorts(
@@ -114,7 +135,7 @@
     std::optional<aidl::android::media::audio::common::AudioPortConfig> getSingleConfigForMixPort(
             bool isInput) const {
         const auto config = generateAudioMixPortConfigs(
-                getMixPorts(isInput, false /*attachedOnly*/), isInput, true);
+                getMixPorts(isInput, false /*connectedOnly*/), isInput, true);
         if (!config.empty()) {
             return *config.begin();
         }
@@ -139,13 +160,20 @@
         return *config.begin();
     }
 
+    ndk::ScopedAStatus onExternalDeviceConnected(
+            aidl::android::hardware::audio::core::IModule* module,
+            const aidl::android::media::audio::common::AudioPort& port);
+    ndk::ScopedAStatus onExternalDeviceDisconnected(
+            aidl::android::hardware::audio::core::IModule* module,
+            const aidl::android::media::audio::common::AudioPort& port);
+
     bool isMmapSupported() const;
 
     std::string toString() const;
 
   private:
     std::vector<aidl::android::media::audio::common::AudioPort> findMixPorts(
-            bool isInput, bool attachedOnly, bool singlePort,
+            bool isInput, bool connectedOnly, bool singlePort,
             const std::function<bool(const aidl::android::media::audio::common::AudioPort&)>& pred)
             const;
     std::vector<aidl::android::media::audio::common::AudioPortConfig> generateAudioMixPortConfigs(
@@ -167,5 +195,7 @@
     std::set<int32_t> mAttachedSinkDevicePorts;
     std::set<int32_t> mAttachedSourceDevicePorts;
     std::set<int32_t> mExternalDevicePorts;
+    std::set<int32_t> mConnectedExternalSinkDevicePorts;
+    std::set<int32_t> mConnectedExternalSourceDevicePorts;
     std::vector<aidl::android::hardware::audio::core::AudioRoute> mRoutes;
 };
diff --git a/audio/aidl/vts/TestUtils.h b/audio/aidl/vts/TestUtils.h
index 10c2fc6..b559669 100644
--- a/audio/aidl/vts/TestUtils.h
+++ b/audio/aidl/vts/TestUtils.h
@@ -78,9 +78,9 @@
     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";                                     \
-        }                                                                                     \
+#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/VtsHalAudioCoreModuleTargetTest.cpp b/audio/aidl/vts/VtsHalAudioCoreModuleTargetTest.cpp
index 8a8998e..9c52d19 100644
--- a/audio/aidl/vts/VtsHalAudioCoreModuleTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalAudioCoreModuleTargetTest.cpp
@@ -46,6 +46,7 @@
 #include <aidl/android/media/audio/common/AudioOutputFlags.h>
 #include <android-base/chrono_utils.h>
 #include <android/binder_enums.h>
+#include <error/expected_utils.h>
 #include <fmq/AidlMessageQueue.h>
 
 #include "AudioHalBinderServiceUtil.h"
@@ -86,6 +87,7 @@
 using aidl::android::media::audio::common::AudioFormatType;
 using aidl::android::media::audio::common::AudioIoFlags;
 using aidl::android::media::audio::common::AudioLatencyMode;
+using aidl::android::media::audio::common::AudioMMapPolicy;
 using aidl::android::media::audio::common::AudioMMapPolicyInfo;
 using aidl::android::media::audio::common::AudioMMapPolicyType;
 using aidl::android::media::audio::common::AudioMode;
@@ -144,28 +146,36 @@
 }
 
 AudioPort GenerateUniqueDeviceAddress(const AudioPort& port) {
+    // Point-to-point connections do not use addresses.
+    static const std::set<std::string> kPointToPointConnections = {
+            AudioDeviceDescription::CONNECTION_ANALOG, AudioDeviceDescription::CONNECTION_HDMI,
+            AudioDeviceDescription::CONNECTION_HDMI_ARC,
+            AudioDeviceDescription::CONNECTION_HDMI_EARC, AudioDeviceDescription::CONNECTION_SPDIF};
     static int nextId = 0;
     using Tag = AudioDeviceAddress::Tag;
+    const auto& deviceDescription = port.ext.get<AudioPortExt::Tag::device>().device.type;
     AudioDeviceAddress address;
-    switch (suggestDeviceAddressTag(port.ext.get<AudioPortExt::Tag::device>().device.type)) {
-        case Tag::id:
-            address = AudioDeviceAddress::make<Tag::id>(std::to_string(++nextId));
-            break;
-        case Tag::mac:
-            address = AudioDeviceAddress::make<Tag::mac>(
-                    std::vector<uint8_t>{1, 2, 3, 4, 5, static_cast<uint8_t>(++nextId & 0xff)});
-            break;
-        case Tag::ipv4:
-            address = AudioDeviceAddress::make<Tag::ipv4>(
-                    std::vector<uint8_t>{192, 168, 0, static_cast<uint8_t>(++nextId & 0xff)});
-            break;
-        case Tag::ipv6:
-            address = AudioDeviceAddress::make<Tag::ipv6>(std::vector<int32_t>{
-                    0xfc00, 0x0123, 0x4567, 0x89ab, 0xcdef, 0, 0, ++nextId & 0xffff});
-            break;
-        case Tag::alsa:
-            address = AudioDeviceAddress::make<Tag::alsa>(std::vector<int32_t>{1, ++nextId});
-            break;
+    if (kPointToPointConnections.count(deviceDescription.connection) == 0) {
+        switch (suggestDeviceAddressTag(deviceDescription)) {
+            case Tag::id:
+                address = AudioDeviceAddress::make<Tag::id>(std::to_string(++nextId));
+                break;
+            case Tag::mac:
+                address = AudioDeviceAddress::make<Tag::mac>(
+                        std::vector<uint8_t>{1, 2, 3, 4, 5, static_cast<uint8_t>(++nextId & 0xff)});
+                break;
+            case Tag::ipv4:
+                address = AudioDeviceAddress::make<Tag::ipv4>(
+                        std::vector<uint8_t>{192, 168, 0, static_cast<uint8_t>(++nextId & 0xff)});
+                break;
+            case Tag::ipv6:
+                address = AudioDeviceAddress::make<Tag::ipv6>(std::vector<int32_t>{
+                        0xfc00, 0x0123, 0x4567, 0x89ab, 0xcdef, 0, 0, ++nextId & 0xffff});
+                break;
+            case Tag::alsa:
+                address = AudioDeviceAddress::make<Tag::alsa>(std::vector<int32_t>{1, ++nextId});
+                break;
+        }
     }
     AudioPort result = port;
     result.ext.get<AudioPortExt::Tag::device>().device.address = std::move(address);
@@ -412,9 +422,21 @@
 
     void SetUpImpl(const std::string& moduleName) {
         ASSERT_NO_FATAL_FAILURE(ConnectToService(moduleName));
+        ASSERT_IS_OK(module->getAudioPorts(&initialPorts));
+        ASSERT_IS_OK(module->getAudioRoutes(&initialRoutes));
     }
 
-    void TearDownImpl() { debug.reset(); }
+    void TearDownImpl() {
+        debug.reset();
+        std::vector<AudioPort> finalPorts;
+        ASSERT_IS_OK(module->getAudioPorts(&finalPorts));
+        EXPECT_NO_FATAL_FAILURE(VerifyVectorsAreEqual<AudioPort>(initialPorts, finalPorts))
+                << "The list of audio ports was not restored to the initial state";
+        std::vector<AudioRoute> finalRoutes;
+        ASSERT_IS_OK(module->getAudioRoutes(&finalRoutes));
+        EXPECT_NO_FATAL_FAILURE(VerifyVectorsAreEqual<AudioRoute>(initialRoutes, finalRoutes))
+                << "The list of audio routes was not restored to the initial state";
+    }
 
     void ConnectToService(const std::string& moduleName) {
         ASSERT_EQ(module, nullptr);
@@ -502,17 +524,24 @@
         }
     }
 
+    // Warning: modifies the vectors!
+    template <typename T>
+    void VerifyVectorsAreEqual(std::vector<T>& v1, std::vector<T>& v2) {
+        ASSERT_EQ(v1.size(), v2.size());
+        std::sort(v1.begin(), v1.end());
+        std::sort(v2.begin(), v2.end());
+        if (v1 != v2) {
+            FAIL() << "Vectors are not equal: v1 = " << ::android::internal::ToString(v1)
+                   << ", v2 = " << ::android::internal::ToString(v2);
+        }
+    }
+
     std::shared_ptr<IModule> module;
     std::unique_ptr<ModuleConfig> moduleConfig;
     AudioHalBinderServiceUtil binderUtil;
     std::unique_ptr<WithDebugFlags> debug;
-};
-
-class AudioCoreModule : public AudioCoreModuleBase, public testing::TestWithParam<std::string> {
-  public:
-    void SetUp() override { ASSERT_NO_FATAL_FAILURE(SetUpImpl(GetParam())); }
-
-    void TearDown() override { ASSERT_NO_FATAL_FAILURE(TearDownImpl()); }
+    std::vector<AudioPort> initialPorts;
+    std::vector<AudioRoute> initialRoutes;
 };
 
 class WithDevicePortConnectedState {
@@ -525,13 +554,24 @@
             EXPECT_IS_OK(mModule->disconnectExternalDevice(getId()))
                     << "when disconnecting device port ID " << getId();
         }
+        if (mModuleConfig != nullptr) {
+            EXPECT_IS_OK(mModuleConfig->onExternalDeviceDisconnected(mModule, mConnectedPort))
+                    << "when external device disconnected";
+        }
     }
-    void SetUp(IModule* module) {
-        ASSERT_IS_OK(module->connectExternalDevice(mIdAndData, &mConnectedPort))
+    ScopedAStatus SetUpNoChecks(IModule* module, ModuleConfig* moduleConfig) {
+        RETURN_STATUS_IF_ERROR(module->connectExternalDevice(mIdAndData, &mConnectedPort));
+        RETURN_STATUS_IF_ERROR(moduleConfig->onExternalDeviceConnected(module, mConnectedPort));
+        mModule = module;
+        mModuleConfig = moduleConfig;
+        return ScopedAStatus::ok();
+    }
+    void SetUp(IModule* module, ModuleConfig* moduleConfig) {
+        ASSERT_NE(moduleConfig, nullptr);
+        ASSERT_IS_OK(SetUpNoChecks(module, moduleConfig))
                 << "when connecting device port ID & data " << mIdAndData.toString();
         ASSERT_NE(mIdAndData.id, getId())
                 << "ID of the connected port must not be the same as the ID of the template port";
-        mModule = module;
     }
     int32_t getId() const { return mConnectedPort.id; }
     const AudioPort& get() { return mConnectedPort; }
@@ -539,9 +579,17 @@
   private:
     const AudioPort mIdAndData;
     IModule* mModule = nullptr;
+    ModuleConfig* mModuleConfig = nullptr;
     AudioPort mConnectedPort;
 };
 
+class AudioCoreModule : public AudioCoreModuleBase, public testing::TestWithParam<std::string> {
+  public:
+    void SetUp() override { ASSERT_NO_FATAL_FAILURE(SetUpImpl(GetParam())); }
+
+    void TearDown() override { ASSERT_NO_FATAL_FAILURE(TearDownImpl()); }
+};
+
 class StreamContext {
   public:
     typedef AidlMessageQueue<StreamDescriptor::Command, SynchronizedReadWrite> CommandMQ;
@@ -1190,11 +1238,25 @@
                    const AudioPortConfig& portConfig2)
         : mSrcPortConfig(sinkIsCfg1 ? portConfig2 : portConfig1),
           mSinkPortConfig(sinkIsCfg1 ? portConfig1 : portConfig2) {}
+    WithAudioPatch(const WithAudioPatch& patch, const AudioPortConfig& srcPortConfig,
+                   const AudioPortConfig& sinkPortConfig)
+        : mInitialPatch(patch.mPatch),
+          mSrcPortConfig(srcPortConfig),
+          mSinkPortConfig(sinkPortConfig),
+          mModule(patch.mModule),
+          mPatch(patch.mPatch) {}
     WithAudioPatch(const WithAudioPatch&) = delete;
     WithAudioPatch& operator=(const WithAudioPatch&) = delete;
     ~WithAudioPatch() {
         if (mModule != nullptr && mPatch.id != 0) {
-            EXPECT_IS_OK(mModule->resetAudioPatch(mPatch.id)) << "patch id " << getId();
+            if (mInitialPatch.has_value()) {
+                AudioPatch ignored;
+                // This releases our port configs so that they can be reset.
+                EXPECT_IS_OK(mModule->setAudioPatch(*mInitialPatch, &ignored))
+                        << "patch id " << mInitialPatch->id;
+            } else {
+                EXPECT_IS_OK(mModule->resetAudioPatch(mPatch.id)) << "patch id " << getId();
+            }
         }
     }
     void SetUpPortConfigs(IModule* module) {
@@ -1216,6 +1278,16 @@
             EXPECT_GT(latencyMs, 0) << "patch id " << getId();
         }
     }
+    void VerifyAgainstAllPatches(IModule* module) {
+        std::vector<AudioPatch> allPatches;
+        ASSERT_IS_OK(module->getAudioPatches(&allPatches));
+        const auto& patchIt = findById(allPatches, getId());
+        ASSERT_NE(patchIt, allPatches.end()) << "patch id " << getId();
+        if (get() != *patchIt) {
+            FAIL() << "Stored patch: " << get().toString() << " is not the same as returned "
+                   << "by the HAL module: " << patchIt->toString();
+        }
+    }
     int32_t getId() const { return mPatch.id; }
     const AudioPatch& get() const { return mPatch; }
     const AudioPortConfig& getSinkPortConfig() const { return mSinkPortConfig.get(); }
@@ -1225,6 +1297,7 @@
     }
 
   private:
+    std::optional<AudioPatch> mInitialPatch;
     WithAudioPortConfig mSrcPortConfig;
     WithAudioPortConfig mSinkPortConfig;
     IModule* mModule = nullptr;
@@ -1249,11 +1322,8 @@
     ASSERT_IS_OK(module->getAudioPorts(&ports1));
     std::vector<AudioPort> ports2;
     ASSERT_IS_OK(module->getAudioPorts(&ports2));
-    ASSERT_EQ(ports1.size(), ports2.size())
-            << "Sizes of audio port arrays do not match across consequent calls to getAudioPorts";
-    std::sort(ports1.begin(), ports1.end());
-    std::sort(ports2.begin(), ports2.end());
-    EXPECT_EQ(ports1, ports2);
+    EXPECT_NO_FATAL_FAILURE(VerifyVectorsAreEqual<AudioPort>(ports1, ports2))
+            << "Audio port arrays do not match across consequent calls to getAudioPorts";
 }
 
 TEST_P(AudioCoreModule, GetAudioRoutesIsStable) {
@@ -1261,11 +1331,8 @@
     ASSERT_IS_OK(module->getAudioRoutes(&routes1));
     std::vector<AudioRoute> routes2;
     ASSERT_IS_OK(module->getAudioRoutes(&routes2));
-    ASSERT_EQ(routes1.size(), routes2.size())
-            << "Sizes of audio route arrays do not match across consequent calls to getAudioRoutes";
-    std::sort(routes1.begin(), routes1.end());
-    std::sort(routes2.begin(), routes2.end());
-    EXPECT_EQ(routes1, routes2);
+    EXPECT_NO_FATAL_FAILURE(VerifyVectorsAreEqual<AudioRoute>(routes1, routes2))
+            << " Audio route arrays do not match across consequent calls to getAudioRoutes";
 }
 
 TEST_P(AudioCoreModule, GetAudioRoutesAreValid) {
@@ -1422,7 +1489,7 @@
     for (const auto& port : ports) {
         AudioPort portWithData = GenerateUniqueDeviceAddress(port);
         WithDevicePortConnectedState portConnected(portWithData);
-        ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get()));
+        ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get(), moduleConfig.get()));
         const int32_t connectedPortId = portConnected.getId();
         ASSERT_NE(portWithData.id, connectedPortId);
         ASSERT_EQ(portWithData.ext.getTag(), portConnected.get().ext.getTag());
@@ -1434,8 +1501,25 @@
                 << "port ID " << connectedPortId;
         EXPECT_EQ(portConnected.get(), connectedPort);
         const auto& portProfiles = connectedPort.profiles;
-        EXPECT_NE(0UL, portProfiles.size())
-                << "Connected port has no profiles: " << connectedPort.toString();
+        if (portProfiles.empty()) {
+            const auto routableMixPorts =
+                    moduleConfig->getRoutableMixPortsForDevicePort(connectedPort);
+            bool hasMixPortWithStaticProfile = false;
+            for (const auto& mixPort : routableMixPorts) {
+                const auto& mixPortProfiles = mixPort.profiles;
+                if (!mixPortProfiles.empty() &&
+                    !std::all_of(mixPortProfiles.begin(), mixPortProfiles.end(),
+                                 [](const auto& profile) {
+                                     return profile.format.type == AudioFormatType::DEFAULT;
+                                 })) {
+                    hasMixPortWithStaticProfile = true;
+                    break;
+                }
+            }
+            EXPECT_TRUE(hasMixPortWithStaticProfile)
+                    << "Connected port has no profiles and no routable mix ports with profiles: "
+                    << connectedPort.toString();
+        }
         const auto dynamicProfileIt =
                 std::find_if(portProfiles.begin(), portProfiles.end(), [](const auto& profile) {
                     return profile.format.type == AudioFormatType::DEFAULT;
@@ -1519,14 +1603,15 @@
         EXPECT_NE(portConfigsAfter.end(), afterIt)
                 << " port config ID " << c.id << " was removed by reset";
         if (afterIt != portConfigsAfter.end()) {
-            EXPECT_EQ(c, *afterIt);
+            EXPECT_TRUE(c == *afterIt)
+                    << "Expected: " << c.toString() << "; Actual: " << afterIt->toString();
         }
     }
 }
 
 TEST_P(AudioCoreModule, SetAudioPortConfigSuggestedConfig) {
     ASSERT_NO_FATAL_FAILURE(SetUpModuleConfig());
-    auto srcMixPort = moduleConfig->getSourceMixPortForAttachedDevice();
+    auto srcMixPort = moduleConfig->getSourceMixPortForConnectedDevice();
     if (!srcMixPort.has_value()) {
         GTEST_SKIP() << "No mix port for attached output devices";
     }
@@ -1578,7 +1663,7 @@
     }
     for (const auto& port : ports) {
         WithDevicePortConnectedState portConnected(GenerateUniqueDeviceAddress(port));
-        ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get()));
+        ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get(), moduleConfig.get()));
         ASSERT_NO_FATAL_FAILURE(
                 ApplyEveryConfig(moduleConfig->getPortConfigsForDevicePort(portConnected.get())));
     }
@@ -1648,7 +1733,7 @@
         GTEST_SKIP() << "No external devices in the module.";
     }
     WithDevicePortConnectedState portConnected(GenerateUniqueDeviceAddress(*ports.begin()));
-    ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get()));
+    ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get(), moduleConfig.get()));
     ModuleDebug midwayDebugChange = debug->flags();
     midwayDebugChange.simulateDeviceConnections = false;
     EXPECT_STATUS(EX_ILLEGAL_STATE, module->setModuleDebug(midwayDebugChange))
@@ -1703,7 +1788,7 @@
                 << "when disconnecting already disconnected device port ID " << port.id;
         AudioPort portWithData = GenerateUniqueDeviceAddress(port);
         WithDevicePortConnectedState portConnected(portWithData);
-        ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get()));
+        ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get(), moduleConfig.get()));
         EXPECT_STATUS(EX_ILLEGAL_ARGUMENT,
                       module->connectExternalDevice(portConnected.get(), &ignored))
                 << "when trying to connect a connected device port "
@@ -1725,7 +1810,7 @@
     }
     for (const auto& port : ports) {
         WithDevicePortConnectedState portConnected(GenerateUniqueDeviceAddress(port));
-        ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get()));
+        ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get(), moduleConfig.get()));
         const auto portConfig = moduleConfig->getSingleConfigForDevicePort(portConnected.get());
         {
             WithAudioPortConfig config(portConfig);
@@ -1753,7 +1838,7 @@
         int32_t connectedPortId;
         {
             WithDevicePortConnectedState portConnected(GenerateUniqueDeviceAddress(port));
-            ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get()));
+            ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get(), moduleConfig.get()));
             connectedPortId = portConnected.getId();
             std::vector<AudioRoute> connectedPortRoutes;
             ASSERT_IS_OK(module->getAudioRoutesForAudioPort(connectedPortId, &connectedPortRoutes))
@@ -1783,39 +1868,151 @@
     }
 }
 
+class RoutedPortsProfilesSnapshot {
+  public:
+    explicit RoutedPortsProfilesSnapshot(int32_t portId) : mPortId(portId) {}
+    void Capture(IModule* module) {
+        std::vector<AudioRoute> routes;
+        ASSERT_IS_OK(module->getAudioRoutesForAudioPort(mPortId, &routes));
+        std::vector<AudioPort> allPorts;
+        ASSERT_IS_OK(module->getAudioPorts(&allPorts));
+        ASSERT_NO_FATAL_FAILURE(GetAllRoutedPorts(routes, allPorts));
+        ASSERT_NO_FATAL_FAILURE(GetProfileSizes());
+    }
+    void VerifyNoProfilesChanges(const RoutedPortsProfilesSnapshot& before) {
+        for (const auto& p : before.mRoutedPorts) {
+            auto beforeIt = before.mPortProfileSizes.find(p.id);
+            ASSERT_NE(beforeIt, before.mPortProfileSizes.end())
+                    << "port ID " << p.id << " not found in the initial profile sizes";
+            EXPECT_EQ(beforeIt->second, mPortProfileSizes[p.id])
+                    << " port " << p.toString() << " has an unexpected profile size change"
+                    << " following an external device connection and disconnection";
+        }
+    }
+    void VerifyProfilesNonEmpty() {
+        for (const auto& p : mRoutedPorts) {
+            EXPECT_NE(0UL, mPortProfileSizes[p.id])
+                    << " port " << p.toString() << " must have had its profiles"
+                    << " populated while having a connected external device";
+        }
+    }
+
+    const std::vector<AudioPort>& getRoutedPorts() const { return mRoutedPorts; }
+
+  private:
+    void GetAllRoutedPorts(const std::vector<AudioRoute>& routes,
+                           std::vector<AudioPort>& allPorts) {
+        for (const auto& r : routes) {
+            if (r.sinkPortId == mPortId) {
+                for (const auto& srcPortId : r.sourcePortIds) {
+                    const auto srcPortIt = findById(allPorts, srcPortId);
+                    ASSERT_NE(allPorts.end(), srcPortIt) << "port ID " << srcPortId;
+                    mRoutedPorts.push_back(*srcPortIt);
+                }
+            } else {
+                const auto sinkPortIt = findById(allPorts, r.sinkPortId);
+                ASSERT_NE(allPorts.end(), sinkPortIt) << "port ID " << r.sinkPortId;
+                mRoutedPorts.push_back(*sinkPortIt);
+            }
+        }
+    }
+    void GetProfileSizes() {
+        std::transform(
+                mRoutedPorts.begin(), mRoutedPorts.end(),
+                std::inserter(mPortProfileSizes, mPortProfileSizes.end()),
+                [](const auto& port) { return std::make_pair(port.id, port.profiles.size()); });
+    }
+
+    const int32_t mPortId;
+    std::vector<AudioPort> mRoutedPorts;
+    std::map<int32_t, size_t> mPortProfileSizes;
+};
+
 // Note: This test relies on simulation of external device connections by the HAL module.
 TEST_P(AudioCoreModule, ExternalDeviceMixPortConfigs) {
     // After an external device has been connected, all mix ports that can be routed
     // to the device port for the connected device must have non-empty profiles.
+    // Since the test connects and disconnects a single device each time, the size
+    // of profiles for all mix ports routed to the device port under test must get back
+    // to the original count once the external device is disconnected.
     ASSERT_NO_FATAL_FAILURE(SetUpModuleConfig());
     std::vector<AudioPort> externalDevicePorts = moduleConfig->getExternalDevicePorts();
     if (externalDevicePorts.empty()) {
         GTEST_SKIP() << "No external devices in the module.";
     }
     for (const auto& port : externalDevicePorts) {
-        WithDevicePortConnectedState portConnected(GenerateUniqueDeviceAddress(port));
-        ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get()));
-        std::vector<AudioRoute> routes;
-        ASSERT_IS_OK(module->getAudioRoutesForAudioPort(portConnected.getId(), &routes));
-        std::vector<AudioPort> allPorts;
-        ASSERT_IS_OK(module->getAudioPorts(&allPorts));
-        for (const auto& r : routes) {
-            if (r.sinkPortId == portConnected.getId()) {
-                for (const auto& srcPortId : r.sourcePortIds) {
-                    const auto srcPortIt = findById(allPorts, srcPortId);
-                    ASSERT_NE(allPorts.end(), srcPortIt) << "port ID " << srcPortId;
-                    EXPECT_NE(0UL, srcPortIt->profiles.size())
-                            << " source port " << srcPortIt->toString() << " must have its profiles"
-                            << " populated following external device connection";
-                }
-            } else {
-                const auto sinkPortIt = findById(allPorts, r.sinkPortId);
-                ASSERT_NE(allPorts.end(), sinkPortIt) << "port ID " << r.sinkPortId;
-                EXPECT_NE(0UL, sinkPortIt->profiles.size())
-                        << " source port " << sinkPortIt->toString() << " must have its"
-                        << " profiles populated following external device connection";
+        SCOPED_TRACE(port.toString());
+        RoutedPortsProfilesSnapshot before(port.id);
+        ASSERT_NO_FATAL_FAILURE(before.Capture(module.get()));
+        if (before.getRoutedPorts().empty()) continue;
+        {
+            WithDevicePortConnectedState portConnected(GenerateUniqueDeviceAddress(port));
+            ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get(), moduleConfig.get()));
+            RoutedPortsProfilesSnapshot connected(portConnected.getId());
+            ASSERT_NO_FATAL_FAILURE(connected.Capture(module.get()));
+            EXPECT_NO_FATAL_FAILURE(connected.VerifyProfilesNonEmpty());
+        }
+        RoutedPortsProfilesSnapshot after(port.id);
+        ASSERT_NO_FATAL_FAILURE(after.Capture(module.get()));
+        EXPECT_NO_FATAL_FAILURE(after.VerifyNoProfilesChanges(before));
+    }
+}
+
+// Note: This test relies on simulation of external device connections by the HAL module.
+TEST_P(AudioCoreModule, TwoExternalDevicesMixPortConfigsNested) {
+    // Ensure that in the case when two external devices are connected to the same
+    // device port, disconnecting one of them does not erase the profiles of routed mix ports.
+    // In this scenario, the connections are "nested."
+    ASSERT_NO_FATAL_FAILURE(SetUpModuleConfig());
+    std::vector<AudioPort> externalDevicePorts = moduleConfig->getExternalDevicePorts();
+    if (externalDevicePorts.empty()) {
+        GTEST_SKIP() << "No external devices in the module.";
+    }
+    for (const auto& port : externalDevicePorts) {
+        SCOPED_TRACE(port.toString());
+        WithDevicePortConnectedState portConnected1(GenerateUniqueDeviceAddress(port));
+        ASSERT_NO_FATAL_FAILURE(portConnected1.SetUp(module.get(), moduleConfig.get()));
+        {
+            // Connect and disconnect another device, if possible. It might not be possible
+            // for point-to-point connections, like analog or SPDIF.
+            WithDevicePortConnectedState portConnected2(GenerateUniqueDeviceAddress(port));
+            if (auto status = portConnected2.SetUpNoChecks(module.get(), moduleConfig.get());
+                !status.isOk()) {
+                continue;
             }
         }
+        RoutedPortsProfilesSnapshot connected(portConnected1.getId());
+        ASSERT_NO_FATAL_FAILURE(connected.Capture(module.get()));
+        EXPECT_NO_FATAL_FAILURE(connected.VerifyProfilesNonEmpty());
+    }
+}
+
+// Note: This test relies on simulation of external device connections by the HAL module.
+TEST_P(AudioCoreModule, TwoExternalDevicesMixPortConfigsInterleaved) {
+    // Ensure that in the case when two external devices are connected to the same
+    // device port, disconnecting one of them does not erase the profiles of routed mix ports.
+    // In this scenario, the connections are "interleaved."
+    ASSERT_NO_FATAL_FAILURE(SetUpModuleConfig());
+    std::vector<AudioPort> externalDevicePorts = moduleConfig->getExternalDevicePorts();
+    if (externalDevicePorts.empty()) {
+        GTEST_SKIP() << "No external devices in the module.";
+    }
+    for (const auto& port : externalDevicePorts) {
+        SCOPED_TRACE(port.toString());
+        auto portConnected1 =
+                std::make_unique<WithDevicePortConnectedState>(GenerateUniqueDeviceAddress(port));
+        ASSERT_NO_FATAL_FAILURE(portConnected1->SetUp(module.get(), moduleConfig.get()));
+        WithDevicePortConnectedState portConnected2(GenerateUniqueDeviceAddress(port));
+        // Connect another device, if possible. It might not be possible for point-to-point
+        // connections, like analog or SPDIF.
+        if (auto status = portConnected2.SetUpNoChecks(module.get(), moduleConfig.get());
+            !status.isOk()) {
+            continue;
+        }
+        portConnected1.reset();
+        RoutedPortsProfilesSnapshot connected(portConnected2.getId());
+        ASSERT_NO_FATAL_FAILURE(connected.Capture(module.get()));
+        EXPECT_NO_FATAL_FAILURE(connected.VerifyProfilesNonEmpty());
     }
 }
 
@@ -1980,7 +2177,13 @@
         std::vector<AudioMMapPolicyInfo> policyInfos;
         EXPECT_IS_OK(module->getMmapPolicyInfos(mmapPolicyType, &policyInfos))
                 << toString(mmapPolicyType);
-        EXPECT_EQ(isMmapSupported, !policyInfos.empty());
+        const bool isMMapSupportedByPolicyInfos =
+                std::find_if(policyInfos.begin(), policyInfos.end(), [](const auto& info) {
+                    return info.mmapPolicy == AudioMMapPolicy::AUTO ||
+                           info.mmapPolicy == AudioMMapPolicy::ALWAYS;
+                }) != policyInfos.end();
+        EXPECT_EQ(isMmapSupported, isMMapSupportedByPolicyInfos)
+                << ::android::internal::ToString(policyInfos);
     }
 }
 
@@ -2459,7 +2662,7 @@
 
     void OpenOverMaxCount() {
         constexpr bool isInput = IOTraits<Stream>::is_input;
-        auto ports = moduleConfig->getMixPorts(isInput, true /*attachedOnly*/);
+        auto ports = moduleConfig->getMixPorts(isInput, true /*connectedOnly*/);
         bool hasSingleRun = false;
         for (const auto& port : ports) {
             const size_t maxStreamCount = port.ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
@@ -2580,7 +2783,7 @@
 
     void HwGainHwVolume() {
         const auto ports =
-                moduleConfig->getMixPorts(IOTraits<Stream>::is_input, true /*attachedOnly*/);
+                moduleConfig->getMixPorts(IOTraits<Stream>::is_input, true /*connectedOnly*/);
         if (ports.empty()) {
             GTEST_SKIP() << "No mix ports";
         }
@@ -2619,7 +2822,7 @@
     // it as an invalid argument, or say that offloaded effects are not supported.
     void AddRemoveEffectInvalidArguments() {
         const auto ports =
-                moduleConfig->getMixPorts(IOTraits<Stream>::is_input, true /*attachedOnly*/);
+                moduleConfig->getMixPorts(IOTraits<Stream>::is_input, true /*connectedOnly*/);
         if (ports.empty()) {
             GTEST_SKIP() << "No mix ports";
         }
@@ -2742,7 +2945,7 @@
     if (!status.isOk()) {
         GTEST_SKIP() << "Microphone info is not supported";
     }
-    const auto ports = moduleConfig->getInputMixPorts(true /*attachedOnly*/);
+    const auto ports = moduleConfig->getInputMixPorts(true /*connectedOnly*/);
     if (ports.empty()) {
         GTEST_SKIP() << "No input mix ports for attached devices";
     }
@@ -2759,7 +2962,7 @@
                                                "non-empty list of active microphones";
         }
         if (auto micDevicePorts = ModuleConfig::getBuiltInMicPorts(
-                    moduleConfig->getAttachedSourceDevicesPortsForMixPort(port));
+                    moduleConfig->getConnectedSourceDevicesPortsForMixPort(port));
             !micDevicePorts.empty()) {
             auto devicePortConfig = moduleConfig->getSingleConfigForDevicePort(micDevicePorts[0]);
             WithAudioPatch patch(true /*isInput*/, stream.getPortConfig(), devicePortConfig);
@@ -2791,7 +2994,7 @@
 
 TEST_P(AudioStreamIn, MicrophoneDirection) {
     using MD = IStreamIn::MicrophoneDirection;
-    const auto ports = moduleConfig->getInputMixPorts(true /*attachedOnly*/);
+    const auto ports = moduleConfig->getInputMixPorts(true /*connectedOnly*/);
     if (ports.empty()) {
         GTEST_SKIP() << "No input mix ports for attached devices";
     }
@@ -2814,7 +3017,7 @@
 }
 
 TEST_P(AudioStreamIn, MicrophoneFieldDimension) {
-    const auto ports = moduleConfig->getInputMixPorts(true /*attachedOnly*/);
+    const auto ports = moduleConfig->getInputMixPorts(true /*connectedOnly*/);
     if (ports.empty()) {
         GTEST_SKIP() << "No input mix ports for attached devices";
     }
@@ -2846,7 +3049,7 @@
 
 TEST_P(AudioStreamOut, OpenTwicePrimary) {
     const auto mixPorts =
-            moduleConfig->getPrimaryMixPorts(true /*attachedOnly*/, true /*singlePort*/);
+            moduleConfig->getPrimaryMixPorts(true /*connectedOnly*/, true /*singlePort*/);
     if (mixPorts.empty()) {
         GTEST_SKIP() << "No primary mix port which could be routed to attached devices";
     }
@@ -2857,7 +3060,7 @@
 
 TEST_P(AudioStreamOut, RequireOffloadInfo) {
     const auto offloadMixPorts =
-            moduleConfig->getOffloadMixPorts(true /*attachedOnly*/, true /*singlePort*/);
+            moduleConfig->getOffloadMixPorts(true /*connectedOnly*/, true /*singlePort*/);
     if (offloadMixPorts.empty()) {
         GTEST_SKIP()
                 << "No mix port for compressed offload that could be routed to attached devices";
@@ -2879,7 +3082,7 @@
 
 TEST_P(AudioStreamOut, RequireAsyncCallback) {
     const auto nonBlockingMixPorts =
-            moduleConfig->getNonBlockingMixPorts(true /*attachedOnly*/, true /*singlePort*/);
+            moduleConfig->getNonBlockingMixPorts(true /*connectedOnly*/, true /*singlePort*/);
     if (nonBlockingMixPorts.empty()) {
         GTEST_SKIP()
                 << "No mix port for non-blocking output that could be routed to attached devices";
@@ -2902,7 +3105,7 @@
 }
 
 TEST_P(AudioStreamOut, AudioDescriptionMixLevel) {
-    const auto ports = moduleConfig->getOutputMixPorts(true /*attachedOnly*/);
+    const auto ports = moduleConfig->getOutputMixPorts(true /*connectedOnly*/);
     if (ports.empty()) {
         GTEST_SKIP() << "No output mix ports";
     }
@@ -2930,7 +3133,7 @@
 }
 
 TEST_P(AudioStreamOut, DualMonoMode) {
-    const auto ports = moduleConfig->getOutputMixPorts(true /*attachedOnly*/);
+    const auto ports = moduleConfig->getOutputMixPorts(true /*connectedOnly*/);
     if (ports.empty()) {
         GTEST_SKIP() << "No output mix ports";
     }
@@ -2954,7 +3157,7 @@
 }
 
 TEST_P(AudioStreamOut, LatencyMode) {
-    const auto ports = moduleConfig->getOutputMixPorts(true /*attachedOnly*/);
+    const auto ports = moduleConfig->getOutputMixPorts(true /*connectedOnly*/);
     if (ports.empty()) {
         GTEST_SKIP() << "No output mix ports";
     }
@@ -2996,7 +3199,7 @@
 TEST_P(AudioStreamOut, PlaybackRate) {
     static const auto kStatuses = {EX_NONE, EX_UNSUPPORTED_OPERATION};
     const auto offloadMixPorts =
-            moduleConfig->getOffloadMixPorts(true /*attachedOnly*/, false /*singlePort*/);
+            moduleConfig->getOffloadMixPorts(true /*connectedOnly*/, false /*singlePort*/);
     if (offloadMixPorts.empty()) {
         GTEST_SKIP()
                 << "No mix port for compressed offload that could be routed to attached devices";
@@ -3066,7 +3269,7 @@
 TEST_P(AudioStreamOut, SelectPresentation) {
     static const auto kStatuses = {EX_ILLEGAL_ARGUMENT, EX_UNSUPPORTED_OPERATION};
     const auto offloadMixPorts =
-            moduleConfig->getOffloadMixPorts(true /*attachedOnly*/, false /*singlePort*/);
+            moduleConfig->getOffloadMixPorts(true /*connectedOnly*/, false /*singlePort*/);
     if (offloadMixPorts.empty()) {
         GTEST_SKIP()
                 << "No mix port for compressed offload that could be routed to attached devices";
@@ -3088,7 +3291,7 @@
 
 TEST_P(AudioStreamOut, UpdateOffloadMetadata) {
     const auto offloadMixPorts =
-            moduleConfig->getOffloadMixPorts(true /*attachedOnly*/, false /*singlePort*/);
+            moduleConfig->getOffloadMixPorts(true /*connectedOnly*/, false /*singlePort*/);
     if (offloadMixPorts.empty()) {
         GTEST_SKIP()
                 << "No mix port for compressed offload that could be routed to attached devices";
@@ -3301,7 +3504,7 @@
     void RunStreamIoCommandsImplSeq1(const AudioPortConfig& portConfig,
                                      std::shared_ptr<StateSequence> commandsAndStates,
                                      bool validatePositionIncrease) {
-        auto devicePorts = moduleConfig->getAttachedDevicesPortsForMixPort(
+        auto devicePorts = moduleConfig->getConnectedDevicesPortsForMixPort(
                 IOTraits<Stream>::is_input, portConfig);
         ASSERT_FALSE(devicePorts.empty());
         auto devicePortConfig = moduleConfig->getSingleConfigForDevicePort(devicePorts[0]);
@@ -3341,7 +3544,7 @@
         typename IOTraits<Stream>::Worker worker(*stream.getContext(), &driver,
                                                  stream.getEventReceiver());
 
-        auto devicePorts = moduleConfig->getAttachedDevicesPortsForMixPort(
+        auto devicePorts = moduleConfig->getConnectedDevicesPortsForMixPort(
                 IOTraits<Stream>::is_input, portConfig);
         ASSERT_FALSE(devicePorts.empty());
         auto devicePortConfig = moduleConfig->getSingleConfigForDevicePort(devicePorts[0]);
@@ -3477,9 +3680,12 @@
                     patches.push_back(
                             std::make_unique<WithAudioPatch>(srcSink.first, srcSink.second));
                     EXPECT_NO_FATAL_FAILURE(patches[patches.size() - 1]->SetUp(module.get()));
+                    EXPECT_NO_FATAL_FAILURE(
+                            patches[patches.size() - 1]->VerifyAgainstAllPatches(module.get()));
                 } else {
                     WithAudioPatch patch(srcSink.first, srcSink.second);
                     EXPECT_NO_FATAL_FAILURE(patch.SetUp(module.get()));
+                    EXPECT_NO_FATAL_FAILURE(patch.VerifyAgainstAllPatches(module.get()));
                 }
             }
         }
@@ -3500,6 +3706,29 @@
         }
     }
 
+    void UpdatePatchPorts(bool isInput) {
+        auto srcSinkGroups = moduleConfig->getRoutableSrcSinkGroups(isInput);
+        if (srcSinkGroups.empty()) {
+            GTEST_SKIP() << "No routes to any attached " << direction(isInput, false) << " devices";
+        }
+        bool hasAtLeastOnePair = false;
+        for (const auto& srcSinkGroup : srcSinkGroups) {
+            const auto& srcSinks = srcSinkGroup.second;
+            if (srcSinks.size() < 2) continue;
+            hasAtLeastOnePair = true;
+            const auto& pair1 = srcSinks[0];
+            const auto& pair2 = srcSinks[1];
+            WithAudioPatch patch(pair1.first, pair1.second);
+            ASSERT_NO_FATAL_FAILURE(patch.SetUp(module.get()));
+            WithAudioPatch update(patch, pair2.first, pair2.second);
+            EXPECT_NO_FATAL_FAILURE(update.SetUp(module.get()));
+            EXPECT_NO_FATAL_FAILURE(update.VerifyAgainstAllPatches(module.get()));
+        }
+        if (!hasAtLeastOnePair) {
+            GTEST_SKIP() << "No routes with multiple sources";
+        }
+    }
+
     void UpdateInvalidPatchId(bool isInput) {
         auto srcSinkGroups = moduleConfig->getRoutableSrcSinkGroups(isInput);
         if (srcSinkGroups.empty()) {
@@ -3539,6 +3768,7 @@
 TEST_PATCH_BOTH_DIRECTIONS(SetPatch);
 TEST_PATCH_BOTH_DIRECTIONS(UpdateInvalidPatchId);
 TEST_PATCH_BOTH_DIRECTIONS(UpdatePatch);
+TEST_PATCH_BOTH_DIRECTIONS(UpdatePatchPorts);
 
 TEST_P(AudioModulePatch, ResetInvalidPatchId) {
     std::set<int32_t> patchIds;
@@ -4006,6 +4236,214 @@
                          android::PrintInstanceNameToString);
 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(AudioModulePatch);
 
+static std::vector<std::string> getRemoteSubmixModuleInstance() {
+    auto instances = android::getAidlHalInstanceNames(IModule::descriptor);
+    for (auto instance : instances) {
+        if (instance.find("r_submix") != std::string::npos)
+            return (std::vector<std::string>{instance});
+    }
+    return {};
+}
+
+template <typename Stream>
+class WithRemoteSubmix {
+  public:
+    WithRemoteSubmix() = default;
+    explicit WithRemoteSubmix(AudioDeviceAddress address) : mAddress(address) {}
+    WithRemoteSubmix(const WithRemoteSubmix&) = delete;
+    WithRemoteSubmix& operator=(const WithRemoteSubmix&) = delete;
+    static std::optional<AudioPort> getRemoteSubmixAudioPort(
+            ModuleConfig* moduleConfig,
+            const std::optional<AudioDeviceAddress>& address = std::nullopt) {
+        AudioDeviceType deviceType = IOTraits<Stream>::is_input ? AudioDeviceType::IN_SUBMIX
+                                                                : AudioDeviceType::OUT_SUBMIX;
+        auto ports = moduleConfig->getAudioPortsForDeviceTypes(
+                std::vector<AudioDeviceType>{deviceType},
+                AudioDeviceDescription::CONNECTION_VIRTUAL);
+        if (ports.empty()) return {};
+        AudioPort port = ports.front();
+        if (address) {
+            port.ext.template get<AudioPortExt::Tag::device>().device.address = address.value();
+        } else {
+            port = GenerateUniqueDeviceAddress(port);
+        }
+        return port;
+    }
+    std::optional<AudioDeviceAddress> getAudioDeviceAddress() const { return mAddress; }
+    void SetUp(IModule* module, ModuleConfig* moduleConfig, const AudioPort& connectedPort) {
+        mModule = module;
+        mModuleConfig = moduleConfig;
+
+        ASSERT_NO_FATAL_FAILURE(SetupPatch(connectedPort));
+        if (!mSkipTest) {
+            // open stream
+            mStream = std::make_unique<WithStream<Stream>>(
+                    mPatch->getPortConfig(IOTraits<Stream>::is_input));
+            ASSERT_NO_FATAL_FAILURE(
+                    mStream->SetUp(mModule, AudioCoreModuleBase::kDefaultBufferSizeFrames));
+        }
+        mAddress = connectedPort.ext.template get<AudioPortExt::Tag::device>().device.address;
+    }
+    void SetUp(IModule* module, ModuleConfig* moduleConfig) {
+        ASSERT_NO_FATAL_FAILURE(SetUpPortConnection(module, moduleConfig));
+        SetUp(module, moduleConfig, mConnectedPort->get());
+    }
+    void sendBurstCommands() {
+        const StreamContext* context = mStream->getContext();
+        StreamLogicDefaultDriver driver(makeBurstCommands(true), context->getFrameSizeBytes());
+        typename IOTraits<Stream>::Worker worker(*context, &driver, mStream->getEventReceiver());
+
+        LOG(DEBUG) << __func__ << ": starting worker...";
+        ASSERT_TRUE(worker.start());
+        LOG(DEBUG) << __func__ << ": joining worker...";
+        worker.join();
+        EXPECT_FALSE(worker.hasError()) << worker.getError();
+        EXPECT_EQ("", driver.getUnexpectedStateTransition());
+        if (IOTraits<Stream>::is_input) {
+            EXPECT_TRUE(driver.hasObservablePositionIncrease());
+        }
+        EXPECT_FALSE(driver.hasRetrogradeObservablePosition());
+    }
+    bool skipTest() const { return mSkipTest; }
+
+  private:
+    /* Connect remote submix external device */
+    void SetUpPortConnection(IModule* module, ModuleConfig* moduleConfig) {
+        auto port = getRemoteSubmixAudioPort(moduleConfig, mAddress);
+        ASSERT_TRUE(port.has_value()) << "Device AudioPort for remote submix not found";
+        mConnectedPort = std::make_unique<WithDevicePortConnectedState>(port.value());
+        ASSERT_NO_FATAL_FAILURE(mConnectedPort->SetUp(module, moduleConfig));
+    }
+    /* Get mix port config for stream and setup patch for it. */
+    void SetupPatch(const AudioPort& connectedPort) {
+        const auto portConfig =
+                mModuleConfig->getSingleConfigForMixPort(IOTraits<Stream>::is_input);
+        if (!portConfig.has_value()) {
+            LOG(DEBUG) << __func__ << ": portConfig not found";
+            mSkipTest = true;
+            return;
+        }
+        auto devicePortConfig = mModuleConfig->getSingleConfigForDevicePort(connectedPort);
+        mPatch = std::make_unique<WithAudioPatch>(IOTraits<Stream>::is_input, portConfig.value(),
+                                                  devicePortConfig);
+        ASSERT_NO_FATAL_FAILURE(mPatch->SetUp(mModule));
+    }
+
+    bool mSkipTest = false;
+    IModule* mModule = nullptr;
+    ModuleConfig* mModuleConfig = nullptr;
+    std::optional<AudioDeviceAddress> mAddress;
+    std::unique_ptr<WithDevicePortConnectedState> mConnectedPort;
+    std::unique_ptr<WithAudioPatch> mPatch;
+    std::unique_ptr<WithStream<Stream>> mStream;
+};
+
+class AudioModuleRemoteSubmix : public AudioCoreModule {
+  public:
+    void SetUp() override {
+        ASSERT_NO_FATAL_FAILURE(AudioCoreModule::SetUp());
+        ASSERT_NO_FATAL_FAILURE(SetUpModuleConfig());
+    }
+
+    void TearDown() override { ASSERT_NO_FATAL_FAILURE(TearDownImpl()); }
+};
+
+TEST_P(AudioModuleRemoteSubmix, OutputDoesNotBlockWhenNoInput) {
+    // open output stream
+    WithRemoteSubmix<IStreamOut> streamOut;
+    ASSERT_NO_FATAL_FAILURE(streamOut.SetUp(module.get(), moduleConfig.get()));
+    if (streamOut.skipTest()) {
+        GTEST_SKIP() << "No mix port for attached devices";
+    }
+    // write something to stream
+    ASSERT_NO_FATAL_FAILURE(streamOut.sendBurstCommands());
+}
+
+TEST_P(AudioModuleRemoteSubmix, OutputDoesNotBlockWhenInputStuck) {
+    // open output stream
+    WithRemoteSubmix<IStreamOut> streamOut;
+    ASSERT_NO_FATAL_FAILURE(streamOut.SetUp(module.get(), moduleConfig.get()));
+    if (streamOut.skipTest()) {
+        GTEST_SKIP() << "No mix port for attached devices";
+    }
+    auto address = streamOut.getAudioDeviceAddress();
+    ASSERT_TRUE(address.has_value());
+
+    // open input stream
+    WithRemoteSubmix<IStreamIn> streamIn(address.value());
+    ASSERT_NO_FATAL_FAILURE(streamIn.SetUp(module.get(), moduleConfig.get()));
+    if (streamIn.skipTest()) {
+        GTEST_SKIP() << "No mix port for attached devices";
+    }
+
+    // write something to stream
+    ASSERT_NO_FATAL_FAILURE(streamOut.sendBurstCommands());
+}
+
+TEST_P(AudioModuleRemoteSubmix, OutputAndInput) {
+    // open output stream
+    WithRemoteSubmix<IStreamOut> streamOut;
+    ASSERT_NO_FATAL_FAILURE(streamOut.SetUp(module.get(), moduleConfig.get()));
+    if (streamOut.skipTest()) {
+        GTEST_SKIP() << "No mix port for attached devices";
+    }
+    auto address = streamOut.getAudioDeviceAddress();
+    ASSERT_TRUE(address.has_value());
+
+    // open input stream
+    WithRemoteSubmix<IStreamIn> streamIn(address.value());
+    ASSERT_NO_FATAL_FAILURE(streamIn.SetUp(module.get(), moduleConfig.get()));
+    if (streamIn.skipTest()) {
+        GTEST_SKIP() << "No mix port for attached devices";
+    }
+
+    // write something to stream
+    ASSERT_NO_FATAL_FAILURE(streamOut.sendBurstCommands());
+    // read from input stream
+    ASSERT_NO_FATAL_FAILURE(streamIn.sendBurstCommands());
+}
+
+TEST_P(AudioModuleRemoteSubmix, OpenInputMultipleTimes) {
+    // open output stream
+    WithRemoteSubmix<IStreamOut> streamOut;
+    ASSERT_NO_FATAL_FAILURE(streamOut.SetUp(module.get(), moduleConfig.get()));
+    if (streamOut.skipTest()) {
+        GTEST_SKIP() << "No mix port for attached devices";
+    }
+    auto address = streamOut.getAudioDeviceAddress();
+    ASSERT_TRUE(address.has_value());
+
+    // connect remote submix input device port
+    auto port = WithRemoteSubmix<IStreamIn>::getRemoteSubmixAudioPort(moduleConfig.get(),
+                                                                      address.value());
+    ASSERT_TRUE(port.has_value()) << "Device AudioPort for remote submix not found";
+    WithDevicePortConnectedState connectedInputPort(port.value());
+    ASSERT_NO_FATAL_FAILURE(connectedInputPort.SetUp(module.get(), moduleConfig.get()));
+
+    // open input streams
+    const int streamInCount = 3;
+    std::vector<std::unique_ptr<WithRemoteSubmix<IStreamIn>>> streamIns(streamInCount);
+    for (int i = 0; i < streamInCount; i++) {
+        streamIns[i] = std::make_unique<WithRemoteSubmix<IStreamIn>>();
+        ASSERT_NO_FATAL_FAILURE(
+                streamIns[i]->SetUp(module.get(), moduleConfig.get(), connectedInputPort.get()));
+        if (streamIns[i]->skipTest()) {
+            GTEST_SKIP() << "No mix port for attached devices";
+        }
+    }
+    // write something to output stream
+    ASSERT_NO_FATAL_FAILURE(streamOut.sendBurstCommands());
+
+    // read from input streams
+    for (int i = 0; i < streamInCount; i++) {
+        ASSERT_NO_FATAL_FAILURE(streamIns[i]->sendBurstCommands());
+    }
+}
+
+INSTANTIATE_TEST_SUITE_P(AudioModuleRemoteSubmixTest, AudioModuleRemoteSubmix,
+                         ::testing::ValuesIn(getRemoteSubmixModuleInstance()));
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(AudioModuleRemoteSubmix);
+
 class TestExecutionTracer : public ::testing::EmptyTestEventListener {
   public:
     void OnTestStart(const ::testing::TestInfo& test_info) override {
diff --git a/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp b/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp
index 3011a5e..1876756 100644
--- a/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp
@@ -42,11 +42,11 @@
 
 using aidl::android::hardware::audio::effect::CommandId;
 using aidl::android::hardware::audio::effect::Descriptor;
+using aidl::android::hardware::audio::effect::Flags;
 using aidl::android::hardware::audio::effect::IEffect;
 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;
@@ -87,11 +87,11 @@
 };
 
 class AudioEffectDataPathTest : public AudioEffectTest {
-    public:
-        void SetUp() override {
-            AudioEffectTest::SetUp();
-            SKIP_TEST_IF_DATA_UNSUPPORTED(mDescriptor.common.flags);
-        }
+  public:
+    void SetUp() override {
+        AudioEffectTest::SetUp();
+        SKIP_TEST_IF_DATA_UNSUPPORTED(mDescriptor.common.flags);
+    }
 };
 
 TEST_P(AudioEffectTest, SetupAndTearDown) {
@@ -504,6 +504,11 @@
 
 // Set and get AudioDeviceDescription in Parameter
 TEST_P(AudioEffectTest, SetAndGetParameterDeviceDescription) {
+    if (!mDescriptor.common.flags.deviceIndication) {
+        GTEST_SKIP() << "Skipping test as effect does not support deviceIndication"
+                     << mDescriptor.common.flags.toString();
+    }
+
     ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
     ASSERT_NO_FATAL_FAILURE(open(mEffect));
 
@@ -527,6 +532,11 @@
 
 // Set and get AudioMode in Parameter
 TEST_P(AudioEffectTest, SetAndGetParameterAudioMode) {
+    if (!mDescriptor.common.flags.audioModeIndication) {
+        GTEST_SKIP() << "Skipping test as effect does not support audioModeIndication"
+                     << mDescriptor.common.flags.toString();
+    }
+
     ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
     ASSERT_NO_FATAL_FAILURE(open(mEffect));
 
@@ -547,6 +557,11 @@
 
 // Set and get AudioSource in Parameter
 TEST_P(AudioEffectTest, SetAndGetParameterAudioSource) {
+    if (!mDescriptor.common.flags.audioSourceIndication) {
+        GTEST_SKIP() << "Skipping test as effect does not support audioSourceIndication"
+                     << mDescriptor.common.flags.toString();
+    }
+
     ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
     ASSERT_NO_FATAL_FAILURE(open(mEffect));
 
@@ -567,6 +582,11 @@
 
 // Set and get VolumeStereo in Parameter
 TEST_P(AudioEffectTest, SetAndGetParameterVolume) {
+    if (mDescriptor.common.flags.volume == Flags::Volume::NONE) {
+        GTEST_SKIP() << "Skipping test as effect does not support volume"
+                     << mDescriptor.common.flags.toString();
+    }
+
     ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
     ASSERT_NO_FATAL_FAILURE(open(mEffect));
 
diff --git a/audio/aidl/vts/VtsHalHapticGeneratorTargetTest.cpp b/audio/aidl/vts/VtsHalHapticGeneratorTargetTest.cpp
index 54caed9..b33234b 100644
--- a/audio/aidl/vts/VtsHalHapticGeneratorTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalHapticGeneratorTargetTest.cpp
@@ -208,7 +208,7 @@
         HapticGeneratorInvalidTest, HapticGeneratorParamTest,
         ::testing::Combine(testing::ValuesIn(EffectFactoryHelper::getAllEffectDescriptors(
                                    IFactory::descriptor, getEffectTypeUuidHapticGenerator())),
-                           testing::Values(MIN_ID - 1),
+                           testing::Values(MIN_ID),
                            testing::Values(HapticGenerator::VibratorScale::NONE),
                            testing::Values(MIN_FLOAT), testing::Values(MIN_FLOAT),
                            testing::Values(MIN_FLOAT)),
diff --git a/audio/core/all-versions/default/PrimaryDevice.cpp b/audio/core/all-versions/default/PrimaryDevice.cpp
index cf162f1..13efbbc 100644
--- a/audio/core/all-versions/default/PrimaryDevice.cpp
+++ b/audio/core/all-versions/default/PrimaryDevice.cpp
@@ -283,7 +283,7 @@
         _hidl_cb(retval, TtyMode::OFF);
         return Void();
     }
-    TtyMode mode = convertTtyModeToHIDL(halMode);
+    TtyMode mode = convertTtyModeToHIDL(halMode.c_str());
     if (mode == TtyMode(-1)) {
         ALOGE("HAL returned invalid TTY value: %s", halMode.c_str());
         _hidl_cb(Result::INVALID_STATE, TtyMode::OFF);
diff --git a/authsecret/1.0/vts/functional/OWNERS b/authsecret/OWNERS
similarity index 98%
rename from authsecret/1.0/vts/functional/OWNERS
rename to authsecret/OWNERS
index ec8c304..5a5d074 100644
--- a/authsecret/1.0/vts/functional/OWNERS
+++ b/authsecret/OWNERS
@@ -1,3 +1,4 @@
 # Bug component: 186411
+
 chengyouho@google.com
 frankwoo@google.com
diff --git a/authsecret/aidl/vts/OWNERS b/authsecret/aidl/vts/OWNERS
deleted file mode 100644
index 40d95e4..0000000
--- a/authsecret/aidl/vts/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-chengyouho@google.com
-frankwoo@google.com
diff --git a/automotive/can/1.0/default/libc++fs/include/automotive/filesystem b/automotive/can/1.0/default/libc++fs/include/automotive/filesystem
index 660ad09..bd3dda5 100644
--- a/automotive/can/1.0/default/libc++fs/include/automotive/filesystem
+++ b/automotive/can/1.0/default/libc++fs/include/automotive/filesystem
@@ -9,6 +9,18 @@
 //===----------------------------------------------------------------------===//
 #ifndef _LIBAUTO_FILESYSTEM
 #define _LIBAUTO_FILESYSTEM
+
+// TODO(152067309): Remove this once the libc++ upgrade is complete.
+#include <__config>
+#if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION > 8000
+
+#include <filesystem>
+namespace android::hardware::automotive {
+namespace filesystem = std::filesystem;
+}
+
+#else
+
 /*
     filesystem synopsis
 
@@ -2696,4 +2708,6 @@
 
 _LIBCPP_POP_MACROS
 
+#endif  // defined(_LIBCPP_VERSION) && _LIBCPP_VERSION > 8000
+
 #endif // _LIBAUTO_FILESYSTEM
diff --git a/automotive/can/1.0/default/libc++fs/src/filesystem/directory_iterator.cpp b/automotive/can/1.0/default/libc++fs/src/filesystem/directory_iterator.cpp
index 37c863b..0dbf492 100644
--- a/automotive/can/1.0/default/libc++fs/src/filesystem/directory_iterator.cpp
+++ b/automotive/can/1.0/default/libc++fs/src/filesystem/directory_iterator.cpp
@@ -6,9 +6,15 @@
 // Source Licenses. See LICENSE.TXT for details.
 //
 //===----------------------------------------------------------------------===//
+
+// TODO(152067309): Remove this once the libc++ upgrade is complete.
+#include <__config>
+#if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION <= 8000
+
 /* clang-format off */
 #include "automotive/filesystem"
 #include <__config>
+
 #if defined(_LIBCPP_WIN32API)
 #define WIN32_LEAN_AND_MEAN
 #include <Windows.h>
@@ -395,3 +401,5 @@
 
 }  // namespace android::hardware::automotive::filesystem
 /* clang-format on */
+
+#endif // defined(_LIBCPP_VERSION) && _LIBCPP_VERSION <= 8000
diff --git a/automotive/can/1.0/default/libc++fs/src/filesystem/operations.cpp b/automotive/can/1.0/default/libc++fs/src/filesystem/operations.cpp
index 404c0bd..6a76bdc 100644
--- a/automotive/can/1.0/default/libc++fs/src/filesystem/operations.cpp
+++ b/automotive/can/1.0/default/libc++fs/src/filesystem/operations.cpp
@@ -6,6 +6,11 @@
 // Source Licenses. See LICENSE.TXT for details.
 //
 //===----------------------------------------------------------------------===//
+
+// TODO(152067309): Remove this once the libc++ upgrade is complete.
+#include <__config>
+#if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION <= 8000
+
 /* clang-format off */
 #include "automotive/filesystem"
 #include <array>
@@ -1771,3 +1776,5 @@
 #endif
 }  // namespace android::hardware::automotive::filesystem
 /* clang-format on */
+
+#endif // defined(_LIBCPP_VERSION) && _LIBCPP_VERSION <= 8000
diff --git a/automotive/evs/OWNERS b/automotive/evs/OWNERS
index 15de48f..4787f0b 100644
--- a/automotive/evs/OWNERS
+++ b/automotive/evs/OWNERS
@@ -1,2 +1,2 @@
 ankitarora@google.com
-jwhpryor@google.com
+changyeon@google.com
diff --git a/automotive/evs/aidl/Android.bp b/automotive/evs/aidl/Android.bp
index bafb4af..3bfe8f3 100644
--- a/automotive/evs/aidl/Android.bp
+++ b/automotive/evs/aidl/Android.bp
@@ -30,7 +30,7 @@
     stability: "vintf",
     imports: [
         "android.hardware.common-V2",
-        "android.hardware.graphics.common-V4",
+        "android.hardware.graphics.common-V5",
     ],
     backend: {
         java: {
@@ -53,14 +53,14 @@
             version: "1",
             imports: [
                 "android.hardware.common-V2",
-                "android.hardware.graphics.common-V4",
+                "android.hardware.graphics.common-V5",
             ],
         },
         {
             version: "2",
             imports: [
                 "android.hardware.common-V2",
-                "android.hardware.graphics.common-V4",
+                "android.hardware.graphics.common-V5",
             ],
         },
 
diff --git a/automotive/evs/aidl/impl/default/Android.bp b/automotive/evs/aidl/impl/default/Android.bp
index 70c523b..6b638a3 100644
--- a/automotive/evs/aidl/impl/default/Android.bp
+++ b/automotive/evs/aidl/impl/default/Android.bp
@@ -21,9 +21,58 @@
     default_applicable_licenses: ["hardware_interfaces_license"],
 }
 
+cc_defaults {
+    name: "android.hardware.automotive.evs-aidl-default-service-default",
+    defaults: ["EvsHalDefaults"],
+    shared_libs: [
+        "android.hardware.graphics.bufferqueue@1.0",
+        "android.hardware.graphics.bufferqueue@2.0",
+        "android.hidl.token@1.0-utils",
+        "libEGL",
+        "libGLESv2",
+        "libbinder_ndk",
+        "libbufferqueueconverter",
+        "libcamera_metadata",
+        "libhardware_legacy",
+        "libhidlbase",
+        "libnativewindow",
+        "libtinyxml2",
+        "libui",
+        "libyuv",
+    ],
+}
+
+cc_library {
+    name: "android.hardware.automotive.evs-aidl-default-service-lib",
+    defaults: ["android.hardware.automotive.evs-aidl-default-service-default"],
+    vendor: true,
+    cflags: [
+        "-DGL_GLEXT_PROTOTYPES",
+        "-DEGL_EGLEXT_PROTOTYPES",
+    ],
+    srcs: [
+        ":libgui_frame_event_aidl",
+        "src/*.cpp",
+    ],
+    exclude_srcs: ["src/service.cpp"],
+    whole_static_libs: [
+        "android.frameworks.automotive.display-V2-ndk",
+        "android.hardware.automotive.evs-V2-ndk",
+        "android.hardware.common-V2-ndk",
+        "libaidlcommonsupport",
+        "libcutils",
+    ],
+    header_libs: [
+        "libgui_aidl_headers",
+    ],
+    local_include_dirs: ["include"],
+    include_dirs: ["frameworks/native/include/"],
+    export_include_dirs: ["include"],
+}
+
 cc_binary {
     name: "android.hardware.automotive.evs-aidl-default-service",
-    defaults: ["EvsHalDefaults"],
+    defaults: ["android.hardware.automotive.evs-aidl-default-service-default"],
     vintf_fragments: ["manifest_evs-default-service.xml"],
     init_rc: ["evs-default-service.rc"],
     vendor: true,
@@ -31,42 +80,11 @@
     cflags: [
         "-DGL_GLEXT_PROTOTYPES",
         "-DEGL_EGLEXT_PROTOTYPES",
-        "-Wall",
-        "-Wextra",
-        "-Werror",
-        "-Wthread-safety",
     ],
-    srcs: [
-        ":libgui_frame_event_aidl",
-        "src/*.cpp",
-    ],
-    shared_libs: [
-        "android.hardware.graphics.bufferqueue@1.0",
-        "android.hardware.graphics.bufferqueue@2.0",
-        "android.hidl.token@1.0-utils",
-        "libEGL",
-        "libGLESv2",
-        "libbase",
-        "libbinder_ndk",
-        "libbufferqueueconverter",
-        "libcamera_metadata",
-        "libhardware_legacy",
-        "libhidlbase",
-        "liblog",
-        "libnativewindow",
-        "libtinyxml2",
-        "libui",
-        "libutils",
-        "libyuv",
-    ],
+    srcs: ["src/service.cpp"],
     static_libs: [
-        "android.frameworks.automotive.display-V1-ndk",
-        "android.hardware.automotive.evs-V2-ndk",
-        "android.hardware.common-V2-ndk",
-        "libaidlcommonsupport",
-        "libcutils",
+        "android.hardware.automotive.evs-aidl-default-service-lib",
     ],
-    local_include_dirs: ["include"],
     include_dirs: ["frameworks/native/include/"],
     required: ["evs_mock_hal_configuration.xml"],
 }
@@ -77,3 +95,31 @@
     src: "resources/evs_mock_configuration.xml",
     sub_dir: "automotive/evs",
 }
+
+cc_test {
+    name: "android.hardware.automotive.evs-aidl-default-service_cam_buffer_test",
+    defaults: ["android.hardware.automotive.evs-aidl-default-service-default"],
+    vendor: true,
+    srcs: ["tests/EvsCameraBufferTest.cpp"],
+    static_libs: [
+        "android.hardware.automotive.evs-aidl-default-service-lib",
+        "libgmock",
+    ],
+    test_suites: [
+        "general-tests",
+    ],
+}
+
+cc_test {
+    name: "android.hardware.automotive.evs-aidl-default-service_cam_state_test",
+    defaults: ["android.hardware.automotive.evs-aidl-default-service-default"],
+    vendor: true,
+    srcs: ["tests/EvsCameraStateTest.cpp"],
+    static_libs: [
+        "android.hardware.automotive.evs-aidl-default-service-lib",
+        "libgmock",
+    ],
+    test_suites: [
+        "general-tests",
+    ],
+}
diff --git a/automotive/evs/aidl/impl/default/include/ConfigManager.h b/automotive/evs/aidl/impl/default/include/ConfigManager.h
index 1d5fe77..37a17dc 100644
--- a/automotive/evs/aidl/impl/default/include/ConfigManager.h
+++ b/automotive/evs/aidl/impl/default/include/ConfigManager.h
@@ -25,8 +25,10 @@
 
 #include <tinyxml2.h>
 
+#include <limits>
 #include <string>
 #include <string_view>
+#include <type_traits>
 #include <unordered_map>
 #include <unordered_set>
 #include <vector>
@@ -54,6 +56,15 @@
     /* Camera device's capabilities and metadata */
     class CameraInfo {
       public:
+        enum class DeviceType : std::int32_t {
+            NONE = 0,
+            MOCK = 1,
+            V4L2 = 2,
+            VIDEO = 3,
+
+            UNKNOWN = std::numeric_limits<std::underlying_type_t<DeviceType>>::max(),
+        };
+
         CameraInfo() : characteristics(nullptr) {}
 
         virtual ~CameraInfo();
@@ -69,6 +80,10 @@
             return characteristics != nullptr;
         }
 
+        static DeviceType deviceTypeFromSV(const std::string_view sv);
+
+        DeviceType deviceType{DeviceType::NONE};
+
         /*
          * List of supported controls that the primary client can program.
          * Paraemters are stored with its valid range
diff --git a/automotive/evs/aidl/impl/default/include/EvsAllCameras.h b/automotive/evs/aidl/impl/default/include/EvsAllCameras.h
new file mode 100644
index 0000000..a76501d
--- /dev/null
+++ b/automotive/evs/aidl/impl/default/include/EvsAllCameras.h
@@ -0,0 +1,20 @@
+/*
+ * 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 "EvsMockCamera.h"
+#include "EvsVideoEmulatedCamera.h"
diff --git a/automotive/evs/aidl/impl/default/include/EvsCamera.h b/automotive/evs/aidl/impl/default/include/EvsCamera.h
new file mode 100644
index 0000000..539d5f6
--- /dev/null
+++ b/automotive/evs/aidl/impl/default/include/EvsCamera.h
@@ -0,0 +1,144 @@
+/*
+ * 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 "EvsCameraBase.h"
+
+#include <aidl/android/hardware/automotive/evs/IEvsCameraStream.h>
+#include <cutils/native_handle.h>
+
+#include <cstddef>
+#include <mutex>
+#include <utility>
+#include <vector>
+
+namespace aidl::android::hardware::automotive::evs::implementation {
+
+class EvsCamera : public EvsCameraBase {
+  private:
+    using Base = EvsCameraBase;
+    using Self = EvsCamera;
+
+  public:
+    using Base::Base;
+
+    ~EvsCamera() override;
+
+    // Methods from ::android::hardware::automotive::evs::IEvsCamera follow.
+    ndk::ScopedAStatus doneWithFrame(const std::vector<evs::BufferDesc>& buffers) override;
+
+    ndk::ScopedAStatus importExternalBuffers(const std::vector<evs::BufferDesc>& buffers,
+                                             int32_t* _aidl_return) override;
+
+    ndk::ScopedAStatus setMaxFramesInFlight(int32_t bufferCount) override;
+
+    ndk::ScopedAStatus startVideoStream(
+            const std::shared_ptr<evs::IEvsCameraStream>& receiver) override;
+
+    ndk::ScopedAStatus stopVideoStream() override;
+
+    ndk::ScopedAStatus pauseVideoStream() override;
+
+    ndk::ScopedAStatus resumeVideoStream() override;
+
+  protected:
+    virtual ::android::status_t allocateOneFrame(buffer_handle_t* handle) = 0;
+
+    virtual void freeOneFrame(const buffer_handle_t handle);
+
+    virtual bool preVideoStreamStart_locked(const std::shared_ptr<evs::IEvsCameraStream>& receiver,
+                                            ndk::ScopedAStatus& status,
+                                            std::unique_lock<std::mutex>& lck);
+
+    virtual bool startVideoStreamImpl_locked(const std::shared_ptr<evs::IEvsCameraStream>& receiver,
+                                             ndk::ScopedAStatus& status,
+                                             std::unique_lock<std::mutex>& lck) = 0;
+
+    virtual bool postVideoStreamStart_locked(const std::shared_ptr<evs::IEvsCameraStream>& receiver,
+                                             ndk::ScopedAStatus& status,
+                                             std::unique_lock<std::mutex>& lck);
+
+    virtual bool preVideoStreamStop_locked(ndk::ScopedAStatus& status,
+                                           std::unique_lock<std::mutex>& lck);
+
+    virtual bool stopVideoStreamImpl_locked(ndk::ScopedAStatus& status,
+                                            std::unique_lock<std::mutex>& lck) = 0;
+
+    virtual bool postVideoStreamStop_locked(ndk::ScopedAStatus& status,
+                                            std::unique_lock<std::mutex>& lck);
+
+    void shutdown() override;
+
+    void closeAllBuffers_unsafe();
+
+    // Returns (ID, handle) if succeeds. (kInvalidBufferID, nullptr) otherwise.
+    [[nodiscard]] std::pair<std::size_t, buffer_handle_t> useBuffer_unsafe();
+
+    void returnBuffer_unsafe(const std::size_t id);
+
+    bool increaseAvailableFrames_unsafe(const buffer_handle_t handle);
+
+    bool decreaseAvailableFrames_unsafe();
+
+    bool setAvailableFrames_unsafe(const std::size_t bufferCount);
+
+    void swapBufferFrames_unsafe(const std::size_t pos1, const std::size_t pos2);
+
+    struct BufferRecord {
+        BufferRecord() = default;
+        BufferRecord(const BufferRecord&) = default;
+        BufferRecord(BufferRecord&&) = default;
+        BufferRecord& operator=(const BufferRecord&) = default;
+        BufferRecord& operator=(BufferRecord&&) = default;
+        ~BufferRecord() = default;
+
+        explicit BufferRecord(buffer_handle_t h) : handle(h) {}
+
+        buffer_handle_t handle{nullptr};
+        bool inUse{false};
+    };
+
+    enum class StreamState {
+        STOPPED = 0,
+        RUNNING = 1,
+        STOPPING = 2,
+        DEAD = 3,
+    };
+
+    StreamState mStreamState{StreamState::STOPPED};
+
+    std::mutex mMutex;
+
+    // Graphics buffers to transfer images, always in the order of:
+    // In use buffers ... available buffers ... unavailable (unallocated) buffers.
+    std::vector<BufferRecord> mBuffers;
+
+    // Double-mapping between buffer position and ID.
+    std::vector<std::size_t> mBufferPosToId;
+    std::vector<std::size_t> mBufferIdToPos;
+
+    std::size_t mAvailableFrames{0};
+    std::size_t mFramesInUse{0};
+
+    // We use all 1's as a reserved invalid buffer ID.
+    static constexpr std::size_t kInvalidBufferID = ~static_cast<std::size_t>(0);
+
+  public:
+    static bool IsBufferIDValid(const std::size_t bufferId) { return ~bufferId; }
+};
+
+}  // namespace aidl::android::hardware::automotive::evs::implementation
diff --git a/automotive/evs/aidl/impl/default/include/EvsCameraBase.h b/automotive/evs/aidl/impl/default/include/EvsCameraBase.h
new file mode 100644
index 0000000..c3e9dfc
--- /dev/null
+++ b/automotive/evs/aidl/impl/default/include/EvsCameraBase.h
@@ -0,0 +1,43 @@
+/*
+ * 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/hardware/automotive/evs/BnEvsCamera.h>
+
+namespace aidl::android::hardware::automotive::evs::implementation {
+
+class EvsCameraBase : public evs::BnEvsCamera {
+  private:
+    using Base = evs::BnEvsCamera;
+    using Self = EvsCameraBase;
+
+  public:
+    using Base::Base;
+
+    ~EvsCameraBase() override = default;
+
+    virtual void shutdown() = 0;
+
+  protected:
+    // This is used for the derived classes and it prevents constructors from direct access
+    // while it allows this class to be instantiated via ndk::SharedRefBase::make<>.
+    struct Sigil {
+        explicit Sigil() = default;
+    };
+};
+
+}  // namespace aidl::android::hardware::automotive::evs::implementation
diff --git a/automotive/evs/aidl/impl/default/include/EvsEnumerator.h b/automotive/evs/aidl/impl/default/include/EvsEnumerator.h
index 259c266..9dcc774 100644
--- a/automotive/evs/aidl/impl/default/include/EvsEnumerator.h
+++ b/automotive/evs/aidl/impl/default/include/EvsEnumerator.h
@@ -17,8 +17,8 @@
 #pragma once
 
 #include "ConfigManager.h"
+#include "EvsCameraBase.h"
 #include "EvsGlDisplay.h"
-#include "EvsMockCamera.h"
 
 #include <aidl/android/frameworks/automotive/display/ICarDisplayProxy.h>
 #include <aidl/android/hardware/automotive/evs/BnEvsEnumerator.h>
@@ -27,6 +27,7 @@
 #include <aidl/android/hardware/automotive/evs/IEvsCamera.h>
 #include <aidl/android/hardware/automotive/evs/IEvsEnumeratorStatusCallback.h>
 #include <aidl/android/hardware/automotive/evs/Stream.h>
+#include <android-base/thread_annotations.h>
 #include <utils/Thread.h>
 
 #include <atomic>
@@ -72,7 +73,7 @@
   private:
     struct CameraRecord {
         evs::CameraDesc desc;
-        std::weak_ptr<EvsMockCamera> activeInstance;
+        std::weak_ptr<EvsCameraBase> activeInstance;
 
         CameraRecord(const char* cameraId) : desc() { desc.id = cameraId; }
     };
diff --git a/automotive/evs/aidl/impl/default/include/EvsGlDisplay.h b/automotive/evs/aidl/impl/default/include/EvsGlDisplay.h
index ceabd9e..0865a04 100644
--- a/automotive/evs/aidl/impl/default/include/EvsGlDisplay.h
+++ b/automotive/evs/aidl/impl/default/include/EvsGlDisplay.h
@@ -23,6 +23,7 @@
 #include <aidl/android/hardware/automotive/evs/BufferDesc.h>
 #include <aidl/android/hardware/automotive/evs/DisplayDesc.h>
 #include <aidl/android/hardware/automotive/evs/DisplayState.h>
+#include <android-base/thread_annotations.h>
 
 #include <thread>
 
diff --git a/automotive/evs/aidl/impl/default/include/EvsMockCamera.h b/automotive/evs/aidl/impl/default/include/EvsMockCamera.h
index 7e010a2..cd68532 100644
--- a/automotive/evs/aidl/impl/default/include/EvsMockCamera.h
+++ b/automotive/evs/aidl/impl/default/include/EvsMockCamera.h
@@ -17,36 +17,36 @@
 #pragma once
 
 #include "ConfigManager.h"
+#include "EvsCamera.h"
 
-#include <aidl/android/hardware/automotive/evs/BnEvsCamera.h>
-#include <aidl/android/hardware/automotive/evs/BufferDesc.h>
 #include <aidl/android/hardware/automotive/evs/CameraDesc.h>
 #include <aidl/android/hardware/automotive/evs/CameraParam.h>
-#include <aidl/android/hardware/automotive/evs/EvsResult.h>
 #include <aidl/android/hardware/automotive/evs/IEvsCameraStream.h>
 #include <aidl/android/hardware/automotive/evs/IEvsDisplay.h>
 #include <aidl/android/hardware/automotive/evs/ParameterRange.h>
 #include <aidl/android/hardware/automotive/evs/Stream.h>
-// #include <android-base/result.h>
 #include <android/hardware_buffer.h>
 #include <ui/GraphicBuffer.h>
 
-#include <functional>
+#include <cstdint>
+#include <memory>
 #include <thread>
+#include <unordered_map>
+#include <vector>
 
 namespace aidl::android::hardware::automotive::evs::implementation {
 
-class EvsMockCamera : public evs::BnEvsCamera {
-    // This prevents constructors from direct access while it allows this class to
-    // be instantiated via ndk::SharedRefBase::make<>.
+class EvsMockCamera : public EvsCamera {
   private:
-    struct Sigil {
-        explicit Sigil() = default;
-    };
+    using Base = EvsCamera;
 
   public:
+    EvsMockCamera(Sigil sigil, const char* deviceName,
+                  std::unique_ptr<ConfigManager::CameraInfo>& camInfo);
+    EvsMockCamera(const EvsMockCamera&) = delete;
+    EvsMockCamera& operator=(const EvsMockCamera&) = delete;
+
     // Methods from ::android::hardware::automotive::evs::IEvsCamera follow.
-    ndk::ScopedAStatus doneWithFrame(const std::vector<evs::BufferDesc>& buffers) override;
     ndk::ScopedAStatus forcePrimaryClient(
             const std::shared_ptr<evs::IEvsDisplay>& display) override;
     ndk::ScopedAStatus getCameraInfo(evs::CameraDesc* _aidl_return) override;
@@ -58,47 +58,37 @@
     ndk::ScopedAStatus getParameterList(std::vector<evs::CameraParam>* _aidl_return) override;
     ndk::ScopedAStatus getPhysicalCameraInfo(const std::string& deviceId,
                                              evs::CameraDesc* _aidl_return) override;
-    ndk::ScopedAStatus importExternalBuffers(const std::vector<evs::BufferDesc>& buffers,
-                                             int32_t* _aidl_return) override;
-    ndk::ScopedAStatus pauseVideoStream() override;
-    ndk::ScopedAStatus resumeVideoStream() override;
     ndk::ScopedAStatus setExtendedInfo(int32_t opaqueIdentifier,
                                        const std::vector<uint8_t>& opaqueValue) override;
     ndk::ScopedAStatus setIntParameter(evs::CameraParam id, int32_t value,
                                        std::vector<int32_t>* effectiveValue) override;
     ndk::ScopedAStatus setPrimaryClient() override;
-    ndk::ScopedAStatus setMaxFramesInFlight(int32_t bufferCount) override;
-    ndk::ScopedAStatus startVideoStream(
-            const std::shared_ptr<evs::IEvsCameraStream>& receiver) override;
-    ndk::ScopedAStatus stopVideoStream() override;
     ndk::ScopedAStatus unsetPrimaryClient() override;
 
+    const evs::CameraDesc& getDesc() { return mDescription; }
+
     static std::shared_ptr<EvsMockCamera> Create(const char* deviceName);
     static std::shared_ptr<EvsMockCamera> Create(
             const char* deviceName, std::unique_ptr<ConfigManager::CameraInfo>& camInfo,
             const evs::Stream* streamCfg = nullptr);
-    EvsMockCamera(const EvsMockCamera&) = delete;
-    EvsMockCamera& operator=(const EvsMockCamera&) = delete;
-
-    virtual ~EvsMockCamera() override;
-    void shutdown();
-
-    const evs::CameraDesc& getDesc() { return mDescription; }
-
-    // Constructors
-    EvsMockCamera(Sigil sigil, const char* deviceName,
-                  std::unique_ptr<ConfigManager::CameraInfo>& camInfo);
 
   private:
-    // These three functions are expected to be called while mAccessLock is held
-    bool setAvailableFrames_Locked(unsigned bufferCount);
-    unsigned increaseAvailableFrames_Locked(unsigned numToAdd);
-    unsigned decreaseAvailableFrames_Locked(unsigned numToRemove);
-
     void generateFrames();
     void fillMockFrame(buffer_handle_t handle, const AHardwareBuffer_Desc* pDesc);
-    void returnBufferLocked(const uint32_t bufferId);
-    ndk::ScopedAStatus stopVideoStream_impl();
+
+    ::android::status_t allocateOneFrame(buffer_handle_t* handle) override;
+
+    bool startVideoStreamImpl_locked(const std::shared_ptr<evs::IEvsCameraStream>& receiver,
+                                     ndk::ScopedAStatus& status,
+                                     std::unique_lock<std::mutex>& lck) override;
+
+    bool stopVideoStreamImpl_locked(ndk::ScopedAStatus& status,
+                                    std::unique_lock<std::mutex>& lck) override;
+
+    bool postVideoStreamStop_locked(ndk::ScopedAStatus& status,
+                                    std::unique_lock<std::mutex>& lck) override;
+
+    void initializeParameters();
 
     CameraDesc mDescription = {};  // The properties of this camera
 
@@ -119,28 +109,6 @@
     // Bytes per line in the buffers
     uint32_t mStride = 0;
 
-    struct BufferRecord {
-        buffer_handle_t handle;
-        bool inUse;
-
-        explicit BufferRecord(buffer_handle_t h) : handle(h), inUse(false){};
-    };
-
-    std::vector<BufferRecord> mBuffers;  // Graphics buffers to transfer images
-    unsigned mFramesAllowed;             // How many buffers are we currently using
-    unsigned mFramesInUse;               // How many buffers are currently outstanding
-
-    enum StreamStateValues {
-        STOPPED,
-        RUNNING,
-        STOPPING,
-        DEAD,
-    };
-    StreamStateValues mStreamState;
-
-    // Synchronization necessary to deconflict mCaptureThread from the main service thread
-    std::mutex mAccessLock;
-
     // Static camera module information
     std::unique_ptr<ConfigManager::CameraInfo>& mCameraInfo;
 
@@ -160,7 +128,6 @@
         int32_t value;
     };
     std::unordered_map<CameraParam, std::shared_ptr<CameraParameterDesc>> mParams;
-    void initializeParameters();
 };
 
 }  // namespace aidl::android::hardware::automotive::evs::implementation
diff --git a/automotive/evs/aidl/impl/default/include/EvsVideoEmulatedCamera.h b/automotive/evs/aidl/impl/default/include/EvsVideoEmulatedCamera.h
new file mode 100644
index 0000000..356a42a
--- /dev/null
+++ b/automotive/evs/aidl/impl/default/include/EvsVideoEmulatedCamera.h
@@ -0,0 +1,108 @@
+/*
+ * 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 "ConfigManager.h"
+#include "EvsCamera.h"
+
+#include <aidl/android/hardware/automotive/evs/BufferDesc.h>
+#include <aidl/android/hardware/automotive/evs/CameraDesc.h>
+#include <aidl/android/hardware/automotive/evs/CameraParam.h>
+#include <aidl/android/hardware/automotive/evs/IEvsCameraStream.h>
+#include <aidl/android/hardware/automotive/evs/IEvsDisplay.h>
+#include <aidl/android/hardware/automotive/evs/ParameterRange.h>
+#include <aidl/android/hardware/automotive/evs/Stream.h>
+
+#include <cstdint>
+#include <memory>
+#include <unordered_map>
+#include <vector>
+
+namespace aidl::android::hardware::automotive::evs::implementation {
+
+class EvsVideoEmulatedCamera : public EvsCamera {
+  public:
+    EvsVideoEmulatedCamera(Sigil sigil, const char* deviceName,
+                           std::unique_ptr<ConfigManager::CameraInfo>& camInfo);
+
+    ~EvsVideoEmulatedCamera() override;
+
+    // Methods from ::android::hardware::automotive::evs::IEvsCamera follow.
+    ndk::ScopedAStatus forcePrimaryClient(
+            const std::shared_ptr<evs::IEvsDisplay>& display) override;
+    ndk::ScopedAStatus getCameraInfo(evs::CameraDesc* _aidl_return) override;
+    ndk::ScopedAStatus getExtendedInfo(int32_t opaqueIdentifier,
+                                       std::vector<uint8_t>* value) override;
+    ndk::ScopedAStatus getIntParameter(evs::CameraParam id, std::vector<int32_t>* value) override;
+    ndk::ScopedAStatus getIntParameterRange(evs::CameraParam id,
+                                            evs::ParameterRange* _aidl_return) override;
+    ndk::ScopedAStatus getParameterList(std::vector<evs::CameraParam>* _aidl_return) override;
+    ndk::ScopedAStatus getPhysicalCameraInfo(const std::string& deviceId,
+                                             evs::CameraDesc* _aidl_return) override;
+    ndk::ScopedAStatus setExtendedInfo(int32_t opaqueIdentifier,
+                                       const std::vector<uint8_t>& opaqueValue) override;
+    ndk::ScopedAStatus setIntParameter(evs::CameraParam id, int32_t value,
+                                       std::vector<int32_t>* effectiveValue) override;
+    ndk::ScopedAStatus setPrimaryClient() override;
+    ndk::ScopedAStatus unsetPrimaryClient() override;
+
+    const evs::CameraDesc& getDesc() { return mDescription; }
+
+    static std::shared_ptr<EvsVideoEmulatedCamera> Create(const char* deviceName);
+    static std::shared_ptr<EvsVideoEmulatedCamera> Create(
+            const char* deviceName, std::unique_ptr<ConfigManager::CameraInfo>& camInfo,
+            const evs::Stream* streamCfg = nullptr);
+
+  private:
+    // For the camera parameters.
+    struct CameraParameterDesc {
+        CameraParameterDesc(int min = 0, int max = 0, int step = 0, int value = 0) {
+            this->range.min = min;
+            this->range.max = max;
+            this->range.step = step;
+            this->value = value;
+        }
+
+        ParameterRange range;
+        int32_t value;
+    };
+
+    void initializeParameters();
+
+    ::android::status_t allocateOneFrame(buffer_handle_t* handle) override;
+
+    bool startVideoStreamImpl_locked(const std::shared_ptr<evs::IEvsCameraStream>& receiver,
+                                     ndk::ScopedAStatus& status,
+                                     std::unique_lock<std::mutex>& lck) override;
+
+    bool stopVideoStreamImpl_locked(ndk::ScopedAStatus& status,
+                                    std::unique_lock<std::mutex>& lck) override;
+
+    // The properties of this camera.
+    CameraDesc mDescription = {};
+
+    // Camera parameters.
+    std::unordered_map<CameraParam, std::shared_ptr<CameraParameterDesc>> mParams;
+
+    // Static camera module information
+    std::unique_ptr<ConfigManager::CameraInfo>& mCameraInfo;
+
+    // For the extended info
+    std::unordered_map<uint32_t, std::vector<uint8_t>> mExtInfo;
+};
+
+}  // namespace aidl::android::hardware::automotive::evs::implementation
diff --git a/automotive/evs/aidl/impl/default/include/GlWrapper.h b/automotive/evs/aidl/impl/default/include/GlWrapper.h
index adb250c..7ff6104 100644
--- a/automotive/evs/aidl/impl/default/include/GlWrapper.h
+++ b/automotive/evs/aidl/impl/default/include/GlWrapper.h
@@ -25,7 +25,7 @@
 #include <aidl/android/frameworks/automotive/display/ICarDisplayProxy.h>
 #include <aidl/android/hardware/automotive/evs/BufferDesc.h>
 #include <android-base/logging.h>
-#include <bufferqueueconverter/BufferQueueConverter.h>
+#include <cutils/native_handle.h>
 
 namespace aidl::android::hardware::automotive::evs::implementation {
 
@@ -33,7 +33,6 @@
 
 class GlWrapper {
   public:
-    GlWrapper() : mSurfaceHolder(::android::SurfaceHolderUniquePtr(nullptr, nullptr)) {}
     bool initialize(const std::shared_ptr<automotivedisplay::ICarDisplayProxy>& svc,
                     uint64_t displayId);
     void shutdown();
@@ -53,9 +52,6 @@
     unsigned getHeight() { return mHeight; };
 
   private:
-    ::android::sp<::android::hardware::graphics::bufferqueue::V2_0::IGraphicBufferProducer>
-            mGfxBufferProducer;
-
     EGLDisplay mDisplay;
     EGLSurface mSurface;
     EGLContext mContext;
@@ -71,9 +67,6 @@
     // Opaque handle for a native hardware buffer defined in
     // frameworks/native/opengl/include/EGL/eglplatform.h
     ANativeWindow* mWindow;
-
-    // Pointer to a Surface wrapper.
-    ::android::SurfaceHolderUniquePtr mSurfaceHolder;
 };
 
 }  // namespace aidl::android::hardware::automotive::evs::implementation
diff --git a/automotive/evs/aidl/impl/default/src/ConfigManager.cpp b/automotive/evs/aidl/impl/default/src/ConfigManager.cpp
index da791ed..ba4cdc0 100644
--- a/automotive/evs/aidl/impl/default/src/ConfigManager.cpp
+++ b/automotive/evs/aidl/impl/default/src/ConfigManager.cpp
@@ -40,6 +40,18 @@
 std::string_view ConfigManager::sConfigOverridePath =
         "/vendor/etc/automotive/evs/evs_configuration_override.xml";
 
+ConfigManager::CameraInfo::DeviceType ConfigManager::CameraInfo::deviceTypeFromSV(
+        const std::string_view sv) {
+    using namespace std::string_view_literals;
+    static const std::unordered_map<std::string_view, DeviceType> nameToType = {
+            {"mock"sv, DeviceType::MOCK},
+            {"v4l2"sv, DeviceType::V4L2},
+            {"video"sv, DeviceType::VIDEO},
+    };
+    const auto search = nameToType.find(sv);
+    return search == nameToType.end() ? DeviceType::UNKNOWN : search->second;
+}
+
 void ConfigManager::printElementNames(const XMLElement* rootElem, const std::string& prefix) const {
     const XMLElement* curElem = rootElem;
 
@@ -128,6 +140,10 @@
         return false;
     }
 
+    if (const auto typeAttr = aDeviceElem->FindAttribute("type")) {
+        aCamera->deviceType = CameraInfo::deviceTypeFromSV(typeAttr->Value());
+    }
+
     /* size information to allocate camera_metadata_t */
     size_t totalEntries = 0;
     size_t totalDataSize = 0;
diff --git a/automotive/evs/aidl/impl/default/src/EvsCamera.cpp b/automotive/evs/aidl/impl/default/src/EvsCamera.cpp
new file mode 100644
index 0000000..bc3bfdd
--- /dev/null
+++ b/automotive/evs/aidl/impl/default/src/EvsCamera.cpp
@@ -0,0 +1,378 @@
+/*
+ * 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 "EvsCamera.h"
+
+#include <aidl/android/hardware/automotive/evs/EvsResult.h>
+#include <aidlcommonsupport/NativeHandle.h>
+#include <android-base/logging.h>
+#include <android/hardware_buffer.h>
+#include <ui/GraphicBufferAllocator.h>
+#include <ui/GraphicBufferMapper.h>
+
+#include <cstddef>
+#include <mutex>
+
+namespace aidl::android::hardware::automotive::evs::implementation {
+
+// Arbitrary limit on number of graphics buffers allowed to be allocated
+// Safeguards against unreasonable resource consumption and provides a testable limit
+constexpr std::size_t kMaxBuffersInFlight = 100;
+
+// Minimum number of buffers to run a video stream
+constexpr int kMinimumBuffersInFlight = 1;
+
+EvsCamera::~EvsCamera() {
+    shutdown();
+}
+
+ndk::ScopedAStatus EvsCamera::doneWithFrame(const std::vector<evs::BufferDesc>& buffers) {
+    std::lock_guard lck(mMutex);
+    for (const auto& desc : buffers) {
+        returnBuffer_unsafe(desc.bufferId);
+    }
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus EvsCamera::importExternalBuffers(const std::vector<evs::BufferDesc>& buffers,
+                                                    int32_t* _aidl_return) {
+    if (buffers.empty()) {
+        LOG(DEBUG) << __func__
+                   << ": Ignoring a request to import external buffers with an empty list.";
+        return ndk::ScopedAStatus::ok();
+    }
+    static auto& mapper = ::android::GraphicBufferMapper::get();
+    std::lock_guard lck(mMutex);
+    std::size_t numBuffersToAdd = std::min(buffers.size(), kMaxBuffersInFlight - mAvailableFrames);
+    if (numBuffersToAdd == 0) {
+        LOG(WARNING) << __func__ << ": The number of buffers has hit the upper limit ("
+                     << kMaxBuffersInFlight << "). Stop importing.";
+        return ndk::ScopedAStatus::ok();
+    } else if (numBuffersToAdd < buffers.size()) {
+        LOG(WARNING) << "Exceeds the limit on the number of buffers. Only " << numBuffersToAdd
+                     << " buffers will be imported. " << buffers.size() << " are asked.";
+    }
+    const size_t before = mAvailableFrames;
+    for (std::size_t idx = 0; idx < numBuffersToAdd; ++idx) {
+        auto& buffer = buffers[idx];
+        const AHardwareBuffer_Desc* pDesc =
+                reinterpret_cast<const AHardwareBuffer_Desc*>(&buffer.buffer.description);
+
+        buffer_handle_t handleToImport = ::android::dupFromAidl(buffer.buffer.handle);
+        buffer_handle_t handleToStore = nullptr;
+        if (handleToImport == nullptr) {
+            LOG(WARNING) << "Failed to duplicate a memory handle. Ignoring a buffer "
+                         << buffer.bufferId;
+            continue;
+        }
+
+        ::android::status_t result =
+                mapper.importBuffer(handleToImport, pDesc->width, pDesc->height, pDesc->layers,
+                                    pDesc->format, pDesc->usage, pDesc->stride, &handleToStore);
+        if (result != ::android::NO_ERROR || handleToStore == nullptr ||
+            !increaseAvailableFrames_unsafe(handleToStore)) {
+            LOG(WARNING) << "Failed to import a buffer " << buffer.bufferId;
+        }
+    }
+    *_aidl_return = mAvailableFrames - before;
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus EvsCamera::setMaxFramesInFlight(int32_t bufferCount) {
+    std::lock_guard lock(mMutex);
+    if (bufferCount < 1) {
+        LOG(ERROR) << "Ignoring setMaxFramesInFlight with less than one buffer requested.";
+        return ndk::ScopedAStatus::fromServiceSpecificError(
+                static_cast<int>(EvsResult::INVALID_ARG));
+    }
+    if (!setAvailableFrames_unsafe(bufferCount)) {
+        LOG(ERROR) << "Failed to adjust the maximum number of frames in flight.";
+        return ndk::ScopedAStatus::fromServiceSpecificError(
+                static_cast<int>(EvsResult::BUFFER_NOT_AVAILABLE));
+    }
+    return ndk::ScopedAStatus::ok();
+}
+
+void EvsCamera::freeOneFrame(const buffer_handle_t handle) {
+    static auto& alloc = ::android::GraphicBufferAllocator::get();
+    alloc.free(handle);
+}
+
+bool EvsCamera::preVideoStreamStart_locked(const std::shared_ptr<evs::IEvsCameraStream>& receiver,
+                                           ndk::ScopedAStatus& status,
+                                           std::unique_lock<std::mutex>& /* lck */) {
+    if (!receiver) {
+        LOG(ERROR) << __func__ << ": Null receiver.";
+        status = ndk::ScopedAStatus::fromServiceSpecificError(
+                static_cast<int>(EvsResult::INVALID_ARG));
+        return false;
+    }
+
+    // If we've been displaced by another owner of the camera, then we can't do anything else
+    if (mStreamState == StreamState::DEAD) {
+        LOG(ERROR) << __func__ << ": Ignoring when camera has been lost.";
+        status = ndk::ScopedAStatus::fromServiceSpecificError(
+                static_cast<int>(EvsResult::OWNERSHIP_LOST));
+        return false;
+    }
+
+    if (mStreamState != StreamState::STOPPED) {
+        LOG(ERROR) << __func__ << ": Ignoring when a stream is already running.";
+        status = ndk::ScopedAStatus::fromServiceSpecificError(
+                static_cast<int>(EvsResult::STREAM_ALREADY_RUNNING));
+        return false;
+    }
+
+    // If the client never indicated otherwise, configure ourselves for a single streaming buffer
+    if (mAvailableFrames < kMinimumBuffersInFlight &&
+        !setAvailableFrames_unsafe(kMinimumBuffersInFlight)) {
+        LOG(ERROR) << __func__ << "Failed to because we could not get a graphics buffer.";
+        status = ndk::ScopedAStatus::fromServiceSpecificError(
+                static_cast<int>(EvsResult::BUFFER_NOT_AVAILABLE));
+        return false;
+    }
+    mStreamState = StreamState::RUNNING;
+    return true;
+}
+
+bool EvsCamera::postVideoStreamStart_locked(
+        const std::shared_ptr<evs::IEvsCameraStream>& /* receiver */,
+        ndk::ScopedAStatus& /* status */, std::unique_lock<std::mutex>& /* lck */) {
+    return true;
+}
+
+bool EvsCamera::preVideoStreamStop_locked(ndk::ScopedAStatus& status,
+                                          std::unique_lock<std::mutex>& /* lck */) {
+    if (mStreamState != StreamState::RUNNING) {
+        // Terminate the stop process because a stream is not running.
+        status = ndk::ScopedAStatus::ok();
+        return false;
+    }
+    mStreamState = StreamState::STOPPING;
+    return true;
+}
+
+bool EvsCamera::postVideoStreamStop_locked(ndk::ScopedAStatus& /* status */,
+                                           std::unique_lock<std::mutex>& /* lck */) {
+    mStreamState = StreamState::STOPPED;
+    return true;
+}
+
+ndk::ScopedAStatus EvsCamera::startVideoStream(
+        const std::shared_ptr<evs::IEvsCameraStream>& receiver) {
+    bool needShutdown = false;
+    auto status = ndk::ScopedAStatus::ok();
+    {
+        std::unique_lock lck(mMutex);
+        if (!preVideoStreamStart_locked(receiver, status, lck)) {
+            return status;
+        }
+
+        if ((!startVideoStreamImpl_locked(receiver, status, lck) ||
+             !postVideoStreamStart_locked(receiver, status, lck)) &&
+            !status.isOk()) {
+            needShutdown = true;
+        }
+    }
+    if (needShutdown) {
+        shutdown();
+    }
+    return status;
+}
+
+ndk::ScopedAStatus EvsCamera::stopVideoStream() {
+    bool needShutdown = false;
+    auto status = ndk::ScopedAStatus::ok();
+    {
+        std::unique_lock lck(mMutex);
+        if ((!preVideoStreamStop_locked(status, lck) || !stopVideoStreamImpl_locked(status, lck) ||
+             !postVideoStreamStop_locked(status, lck)) &&
+            !status.isOk()) {
+            needShutdown = true;
+        }
+    }
+    if (needShutdown) {
+        shutdown();
+    }
+    return status;
+}
+
+ndk::ScopedAStatus EvsCamera::pauseVideoStream() {
+    return ndk::ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::NOT_SUPPORTED));
+}
+
+ndk::ScopedAStatus EvsCamera::resumeVideoStream() {
+    return ndk::ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::NOT_SUPPORTED));
+}
+
+bool EvsCamera::setAvailableFrames_unsafe(const std::size_t bufferCount) {
+    if (bufferCount < 1) {
+        LOG(ERROR) << "Ignoring request to set buffer count to zero.";
+        return false;
+    }
+    if (bufferCount > kMaxBuffersInFlight) {
+        LOG(ERROR) << "Rejecting buffer request in excess of internal limit";
+        return false;
+    }
+
+    if (bufferCount > mAvailableFrames) {
+        bool success = true;
+        const std::size_t numBufferBeforeAlloc = mAvailableFrames;
+        for (int numBufferToAllocate = bufferCount - mAvailableFrames;
+             success && numBufferToAllocate > 0; --numBufferToAllocate) {
+            buffer_handle_t handle = nullptr;
+            const auto result = allocateOneFrame(&handle);
+            if (result != ::android::NO_ERROR || !handle) {
+                LOG(ERROR) << __func__ << ": Failed to allocate a graphics buffer. Error " << result
+                           << ", handle: " << handle;
+                success = false;
+                break;
+            }
+            success &= increaseAvailableFrames_unsafe(handle);
+        }
+        if (!success) {
+            // Rollback when failure.
+            for (int numBufferToRelease = mAvailableFrames - numBufferBeforeAlloc;
+                 numBufferToRelease > 0; --numBufferToRelease) {
+                decreaseAvailableFrames_unsafe();
+            }
+            return false;
+        }
+    } else {
+        for (int numBufferToRelease = mAvailableFrames - std::max(bufferCount, mFramesInUse);
+             numBufferToRelease > 0; --numBufferToRelease) {
+            decreaseAvailableFrames_unsafe();
+        }
+        if (mAvailableFrames > bufferCount) {
+            // This shouldn't happen with a properly behaving client because the client
+            // should only make this call after returning sufficient outstanding buffers
+            // to allow a clean resize.
+            LOG(ERROR) << "Buffer queue shrink failed, asked: " << bufferCount
+                       << ", actual: " << mAvailableFrames
+                       << " -- too many buffers currently in use?";
+        }
+    }
+    return true;
+}
+
+void EvsCamera::shutdown() {
+    stopVideoStream();
+    std::lock_guard lck(mMutex);
+    closeAllBuffers_unsafe();
+    mStreamState = StreamState::DEAD;
+}
+
+void EvsCamera::closeAllBuffers_unsafe() {
+    if (mFramesInUse > 0) {
+        LOG(WARNING) << __func__ << ": Closing while " << mFramesInUse
+                     << " frame(s) are still in use.";
+    }
+    for (auto& buffer : mBuffers) {
+        freeOneFrame(buffer.handle);
+        buffer.handle = nullptr;
+    }
+    mBuffers.clear();
+    mBufferPosToId.clear();
+    mBufferIdToPos.clear();
+}
+
+std::pair<std::size_t, buffer_handle_t> EvsCamera::useBuffer_unsafe() {
+    if (mFramesInUse >= mAvailableFrames) {
+        DCHECK_EQ(mFramesInUse, mAvailableFrames);
+        return {kInvalidBufferID, nullptr};
+    }
+    const std::size_t pos = mFramesInUse++;
+    auto& buffer = mBuffers[pos];
+    DCHECK(!buffer.inUse);
+    DCHECK(buffer.handle);
+    buffer.inUse = true;
+    return {mBufferPosToId[pos], buffer.handle};
+}
+
+void EvsCamera::returnBuffer_unsafe(const std::size_t id) {
+    if (id >= mBuffers.size()) {
+        LOG(ERROR) << __func__ << ": ID out-of-bound. id: " << id
+                   << " max: " << mBuffers.size() - 1;
+        return;
+    }
+    const std::size_t pos = mBufferIdToPos[id];
+
+    if (!mBuffers[pos].inUse) {
+        LOG(ERROR) << __func__ << ": Ignoring returning frame " << id << " which is already free.";
+        return;
+    }
+    DCHECK_LT(pos, mFramesInUse);
+    const std::size_t last_in_use_pos = --mFramesInUse;
+    swapBufferFrames_unsafe(pos, last_in_use_pos);
+    mBuffers[last_in_use_pos].inUse = false;
+}
+
+bool EvsCamera::increaseAvailableFrames_unsafe(const buffer_handle_t handle) {
+    if (mAvailableFrames >= kMaxBuffersInFlight) {
+        LOG(WARNING) << __func__ << ": The number of buffers has hit the upper limit ("
+                     << kMaxBuffersInFlight << "). Stop increasing.";
+        return false;
+    }
+    const std::size_t pos = mAvailableFrames++;
+    if (mAvailableFrames > mBuffers.size()) {
+        const std::size_t oldBufferSize = mBuffers.size();
+        mBuffers.resize(mAvailableFrames);
+        mBufferPosToId.resize(mAvailableFrames);
+        mBufferIdToPos.resize(mAvailableFrames);
+        // Build position/ID mapping.
+        for (std::size_t idx = oldBufferSize; idx < mBuffers.size(); ++idx) {
+            mBufferPosToId[idx] = idx;
+            mBufferIdToPos[idx] = idx;
+        }
+    }
+    auto& buffer = mBuffers[pos];
+    DCHECK(!buffer.inUse);
+    DCHECK(!buffer.handle);
+    buffer.handle = handle;
+    return true;
+}
+
+bool EvsCamera::decreaseAvailableFrames_unsafe() {
+    if (mFramesInUse >= mAvailableFrames) {
+        DCHECK_EQ(mFramesInUse, mAvailableFrames);
+        return false;
+    }
+    const std::size_t pos = --mAvailableFrames;
+    auto& buffer = mBuffers[pos];
+    DCHECK(!buffer.inUse);
+    DCHECK(buffer.handle);
+    freeOneFrame(buffer.handle);
+    buffer.handle = nullptr;
+    return true;
+}
+
+void EvsCamera::swapBufferFrames_unsafe(const std::size_t pos1, const std::size_t pos2) {
+    if (pos1 == pos2) {
+        return;
+    }
+    if (pos1 >= mBuffers.size() || pos2 >= mBuffers.size()) {
+        LOG(ERROR) << __func__ << ": Index out-of-bound. pos1: " << pos1 << ", pos2: " << pos2
+                   << ", buffer size: " << mBuffers.size();
+        return;
+    }
+    const std::size_t id1 = mBufferPosToId[pos1];
+    const std::size_t id2 = mBufferPosToId[pos2];
+    std::swap(mBufferPosToId[pos1], mBufferPosToId[pos2]);
+    std::swap(mBufferIdToPos[id1], mBufferIdToPos[id2]);
+    std::swap(mBuffers[pos1], mBuffers[pos2]);
+}
+
+}  // namespace aidl::android::hardware::automotive::evs::implementation
diff --git a/automotive/evs/aidl/impl/default/src/EvsEnumerator.cpp b/automotive/evs/aidl/impl/default/src/EvsEnumerator.cpp
index 5178958..80e72a7 100644
--- a/automotive/evs/aidl/impl/default/src/EvsEnumerator.cpp
+++ b/automotive/evs/aidl/impl/default/src/EvsEnumerator.cpp
@@ -17,8 +17,9 @@
 #include "EvsEnumerator.h"
 
 #include "ConfigManager.h"
+#include "EvsAllCameras.h"
+#include "EvsCameraBase.h"
 #include "EvsGlDisplay.h"
-#include "EvsMockCamera.h"
 
 #include <aidl/android/hardware/automotive/evs/EvsResult.h>
 #include <aidl/android/hardware/graphics/common/BufferUsage.h>
@@ -243,7 +244,7 @@
     }
 
     // Has this camera already been instantiated by another caller?
-    std::shared_ptr<EvsMockCamera> pActiveCamera = pRecord->activeInstance.lock();
+    std::shared_ptr<EvsCameraBase> pActiveCamera = pRecord->activeInstance.lock();
     if (pActiveCamera) {
         LOG(WARNING) << "Killing previous camera because of new caller";
         closeCamera(pActiveCamera);
@@ -253,12 +254,31 @@
     if (!sConfigManager) {
         pActiveCamera = EvsMockCamera::Create(id.data());
     } else {
-        pActiveCamera = EvsMockCamera::Create(id.data(), sConfigManager->getCameraInfo(id), &cfg);
+        auto& cameraInfo = sConfigManager->getCameraInfo(id);
+        switch (cameraInfo->deviceType) {
+            using DeviceType = ConfigManager::CameraInfo::DeviceType;
+
+            // Default to MOCK for backward compatibility.
+            case DeviceType::NONE:
+            case DeviceType::MOCK:
+                pActiveCamera = EvsMockCamera::Create(id.data(), cameraInfo, &cfg);
+                break;
+
+            case DeviceType::VIDEO:
+                pActiveCamera = EvsVideoEmulatedCamera::Create(id.data(), cameraInfo, &cfg);
+                break;
+
+            default:
+                LOG(ERROR) << __func__ << ": camera device type "
+                           << static_cast<std::int32_t>(cameraInfo->deviceType)
+                           << " is not supported.";
+                break;
+        }
     }
 
     pRecord->activeInstance = pActiveCamera;
     if (!pActiveCamera) {
-        LOG(ERROR) << "Failed to create new EvsMockCamera object for " << id;
+        LOG(ERROR) << "Failed to create new EVS camera object for " << id;
         return ScopedAStatus::fromServiceSpecificError(
                 static_cast<int>(EvsResult::UNDERLYING_SERVICE_ERROR));
     }
@@ -445,7 +465,7 @@
     if (!pRecord) {
         LOG(ERROR) << "Asked to close a camera whose name isn't recognized";
     } else {
-        std::shared_ptr<EvsMockCamera> pActiveCamera = pRecord->activeInstance.lock();
+        std::shared_ptr<EvsCameraBase> pActiveCamera = pRecord->activeInstance.lock();
         if (!pActiveCamera) {
             LOG(WARNING) << "Somehow a camera is being destroyed "
                          << "when the enumerator didn't know one existed";
diff --git a/automotive/evs/aidl/impl/default/src/EvsGlDisplay.cpp b/automotive/evs/aidl/impl/default/src/EvsGlDisplay.cpp
index e5f8e4c..5b5cbcc 100644
--- a/automotive/evs/aidl/impl/default/src/EvsGlDisplay.cpp
+++ b/automotive/evs/aidl/impl/default/src/EvsGlDisplay.cpp
@@ -352,8 +352,8 @@
     BufferDesc bufferDescToSend = {
             .buffer =
                     {
-                            .handle = std::move(::android::dupToAidl(mBuffer.handle)),
                             .description = mBuffer.description,
+                            .handle = std::move(::android::dupToAidl(mBuffer.handle)),
                     },
             .pixelSizeBytes = 4,  // RGBA_8888 is 4-byte-per-pixel format
             .bufferId = mBuffer.fingerprint,
diff --git a/automotive/evs/aidl/impl/default/src/EvsMockCamera.cpp b/automotive/evs/aidl/impl/default/src/EvsMockCamera.cpp
index 797b221..ef43925 100644
--- a/automotive/evs/aidl/impl/default/src/EvsMockCamera.cpp
+++ b/automotive/evs/aidl/impl/default/src/EvsMockCamera.cpp
@@ -15,28 +15,25 @@
  */
 
 #include "EvsMockCamera.h"
-#include "ConfigManager.h"
-#include "EvsEnumerator.h"
+
+#include <aidl/android/hardware/automotive/evs/EvsResult.h>
 
 #include <aidlcommonsupport/NativeHandle.h>
+#include <android-base/logging.h>
 #include <ui/GraphicBufferAllocator.h>
 #include <ui/GraphicBufferMapper.h>
 #include <utils/SystemClock.h>
 
+#include <cstddef>
+#include <cstdint>
 #include <memory>
+#include <tuple>
 
 namespace {
 
 using ::aidl::android::hardware::graphics::common::BufferUsage;
 using ::ndk::ScopedAStatus;
 
-// Arbitrary limit on number of graphics buffers allowed to be allocated
-// Safeguards against unreasonable resource consumption and provides a testable limit
-constexpr unsigned kMaxBuffersInFlight = 100;
-
-// Minimum number of buffers to run a video stream
-constexpr int kMinimumBuffersInFlight = 1;
-
 // Colors for the colorbar test pattern in ABGR format
 constexpr uint32_t kColors[] = {
         0xFFFFFFFF,  // white
@@ -56,7 +53,7 @@
 
 EvsMockCamera::EvsMockCamera([[maybe_unused]] Sigil sigil, const char* id,
                              std::unique_ptr<ConfigManager::CameraInfo>& camInfo)
-    : mFramesAllowed(0), mFramesInUse(0), mStreamState(STOPPED), mCameraInfo(camInfo) {
+    : mCameraInfo(camInfo) {
     LOG(DEBUG) << __FUNCTION__;
 
     /* set a camera id */
@@ -73,11 +70,6 @@
     initializeParameters();
 }
 
-EvsMockCamera::~EvsMockCamera() {
-    LOG(DEBUG) << __FUNCTION__;
-    shutdown();
-}
-
 void EvsMockCamera::initializeParameters() {
     mParams.emplace(
             CameraParam::BRIGHTNESS,
@@ -90,35 +82,6 @@
             new CameraParameterDesc(/* min= */ 0, /* max= */ 255, /* step= */ 1, /* value= */ 255));
 }
 
-// This gets called if another caller "steals" ownership of the camera
-void EvsMockCamera::shutdown() {
-    LOG(DEBUG) << __FUNCTION__;
-
-    // Make sure our output stream is cleaned up
-    // (It really should be already)
-    stopVideoStream_impl();
-
-    // Claim the lock while we work on internal state
-    std::lock_guard lock(mAccessLock);
-
-    // Drop all the graphics buffers we've been using
-    if (mBuffers.size() > 0) {
-        ::android::GraphicBufferAllocator& alloc(::android::GraphicBufferAllocator::get());
-        for (auto&& rec : mBuffers) {
-            if (rec.inUse) {
-                LOG(WARNING) << "WARNING: releasing a buffer remotely owned.";
-            }
-            alloc.free(rec.handle);
-            rec.handle = nullptr;
-        }
-        mBuffers.clear();
-    }
-
-    // Put this object into an unrecoverable error state since somebody else
-    // is going to own the underlying camera now
-    mStreamState = DEAD;
-}
-
 // Methods from ::aidl::android::hardware::automotive::evs::IEvsCamera follow.
 ScopedAStatus EvsMockCamera::getCameraInfo(CameraDesc* _aidl_return) {
     LOG(DEBUG) << __FUNCTION__;
@@ -128,115 +91,6 @@
     return ScopedAStatus::ok();
 }
 
-ScopedAStatus EvsMockCamera::setMaxFramesInFlight(int32_t bufferCount) {
-    LOG(DEBUG) << __FUNCTION__ << ", bufferCount = " << bufferCount;
-    ;
-
-    std::lock_guard lock(mAccessLock);
-
-    // If we've been displaced by another owner of the camera, then we can't do anything else
-    if (mStreamState == DEAD) {
-        LOG(ERROR) << "Ignoring setMaxFramesInFlight call when camera has been lost.";
-        return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::OWNERSHIP_LOST));
-    }
-
-    // We cannot function without at least one video buffer to send data
-    if (bufferCount < 1) {
-        LOG(ERROR) << "Ignoring setMaxFramesInFlight with less than one buffer requested.";
-        return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::INVALID_ARG));
-    }
-
-    // Update our internal state
-    if (!setAvailableFrames_Locked(bufferCount)) {
-        LOG(ERROR) << "Failed to adjust the maximum number of frames in flight.";
-        return ScopedAStatus::fromServiceSpecificError(
-                static_cast<int>(EvsResult::BUFFER_NOT_AVAILABLE));
-    }
-
-    return ScopedAStatus::ok();
-}
-
-ScopedAStatus EvsMockCamera::startVideoStream(const std::shared_ptr<IEvsCameraStream>& cb) {
-    LOG(DEBUG) << __FUNCTION__;
-
-    if (!cb) {
-        LOG(ERROR) << "A given stream callback is invalid.";
-        return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::INVALID_ARG));
-    }
-
-    std::lock_guard lock(mAccessLock);
-
-    // If we've been displaced by another owner of the camera, then we can't do anything else
-    if (mStreamState == DEAD) {
-        LOG(ERROR) << "Ignoring startVideoStream call when camera has been lost.";
-        return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::OWNERSHIP_LOST));
-    }
-
-    if (mStreamState != STOPPED) {
-        LOG(ERROR) << "Ignoring startVideoStream call when a stream is already running.";
-        return ScopedAStatus::fromServiceSpecificError(
-                static_cast<int>(EvsResult::STREAM_ALREADY_RUNNING));
-    }
-
-    // If the client never indicated otherwise, configure ourselves for a single streaming buffer
-    if (mFramesAllowed < kMinimumBuffersInFlight &&
-        !setAvailableFrames_Locked(kMinimumBuffersInFlight)) {
-        LOG(ERROR) << "Failed to start stream because we couldn't get a graphics buffer";
-        return ScopedAStatus::fromServiceSpecificError(
-                static_cast<int>(EvsResult::BUFFER_NOT_AVAILABLE));
-    }
-
-    // Record the user's callback for use when we have a frame ready
-    mStream = cb;
-
-    // Start the frame generation thread
-    mStreamState = RUNNING;
-    mCaptureThread = std::thread([this]() { generateFrames(); });
-
-    return ScopedAStatus::ok();
-}
-
-ScopedAStatus EvsMockCamera::doneWithFrame(const std::vector<BufferDesc>& list) {
-    std::lock_guard lock(mAccessLock);
-    for (const auto& desc : list) {
-        returnBufferLocked(desc.bufferId);
-    }
-
-    return ScopedAStatus::ok();
-}
-
-ScopedAStatus EvsMockCamera::stopVideoStream() {
-    LOG(DEBUG) << __FUNCTION__;
-    return stopVideoStream_impl();
-}
-
-ScopedAStatus EvsMockCamera::stopVideoStream_impl() {
-    std::unique_lock lock(mAccessLock);
-
-    if (mStreamState != RUNNING) {
-        // Safely return here because a stream is not running.
-        return ScopedAStatus::ok();
-    }
-
-    // Tell the GenerateFrames loop we want it to stop
-    mStreamState = STOPPING;
-
-    // Block outside the mutex until the "stop" flag has been acknowledged
-    // We won't send any more frames, but the client might still get some already in flight
-    LOG(DEBUG) << "Waiting for stream thread to end...";
-    lock.unlock();
-    if (mCaptureThread.joinable()) {
-        mCaptureThread.join();
-    }
-    lock.lock();
-
-    mStreamState = STOPPED;
-    mStream = nullptr;
-    LOG(DEBUG) << "Stream marked STOPPED.";
-
-    return ScopedAStatus::ok();
-}
-
 ScopedAStatus EvsMockCamera::getExtendedInfo(int32_t opaqueIdentifier,
                                              std::vector<uint8_t>* opaqueValue) {
     const auto it = mExtInfo.find(opaqueIdentifier);
@@ -264,14 +118,6 @@
     return ScopedAStatus::ok();
 }
 
-ScopedAStatus EvsMockCamera::pauseVideoStream() {
-    return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::NOT_SUPPORTED));
-}
-
-ScopedAStatus EvsMockCamera::resumeVideoStream() {
-    return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::NOT_SUPPORTED));
-}
-
 ScopedAStatus EvsMockCamera::setPrimaryClient() {
     /* Because EVS HW module reference implementation expects a single client at
      * a time, this returns a success code always.
@@ -346,232 +192,27 @@
     return ScopedAStatus::ok();
 }
 
-ScopedAStatus EvsMockCamera::importExternalBuffers(const std::vector<BufferDesc>& buffers,
-                                                   int32_t* _aidl_return) {
-    size_t numBuffersToAdd = buffers.size();
-    if (numBuffersToAdd < 1) {
-        LOG(DEBUG) << "Ignoring a request to import external buffers with an empty list.";
-        return ScopedAStatus::ok();
-    }
-
-    std::lock_guard lock(mAccessLock);
-    if (numBuffersToAdd > (kMaxBuffersInFlight - mFramesAllowed)) {
-        numBuffersToAdd -= (kMaxBuffersInFlight - mFramesAllowed);
-        LOG(WARNING) << "Exceed the limit on the number of buffers. " << numBuffersToAdd
-                     << " buffers will be imported only.";
-    }
-
-    ::android::GraphicBufferMapper& mapper = ::android::GraphicBufferMapper::get();
-    const size_t before = mFramesAllowed;
-    for (size_t i = 0; i < numBuffersToAdd; ++i) {
-        auto& b = buffers[i];
-        const AHardwareBuffer_Desc* pDesc =
-                reinterpret_cast<const AHardwareBuffer_Desc*>(&b.buffer.description);
-
-        buffer_handle_t handleToImport = ::android::dupFromAidl(b.buffer.handle);
-        buffer_handle_t handleToStore = nullptr;
-        if (handleToImport == nullptr) {
-            LOG(WARNING) << "Failed to duplicate a memory handle. Ignoring a buffer " << b.bufferId;
-            continue;
-        }
-
-        ::android::status_t result =
-                mapper.importBuffer(handleToImport, pDesc->width, pDesc->height, pDesc->layers,
-                                    pDesc->format, pDesc->usage, pDesc->stride, &handleToStore);
-        if (result != ::android::NO_ERROR || handleToStore == nullptr) {
-            LOG(WARNING) << "Failed to import a buffer " << b.bufferId;
-            continue;
-        }
-
-        bool stored = false;
-        for (auto&& rec : mBuffers) {
-            if (rec.handle != nullptr) {
-                continue;
-            }
-
-            // Use this existing entry.
-            rec.handle = handleToStore;
-            rec.inUse = false;
-            stored = true;
-            break;
-        }
-
-        if (!stored) {
-            // Add a BufferRecord wrapping this handle to our set of available buffers.
-            mBuffers.push_back(BufferRecord(handleToStore));
-        }
-        ++mFramesAllowed;
-    }
-
-    *_aidl_return = mFramesAllowed - before;
-    return ScopedAStatus::ok();
-}
-
-bool EvsMockCamera::setAvailableFrames_Locked(unsigned bufferCount) {
-    if (bufferCount < 1) {
-        LOG(ERROR) << "Ignoring request to set buffer count to zero";
-        return false;
-    }
-    if (bufferCount > kMaxBuffersInFlight) {
-        LOG(ERROR) << "Rejecting buffer request in excess of internal limit";
-        return false;
-    }
-
-    // Is an increase required?
-    if (mFramesAllowed < bufferCount) {
-        // An increase is required
-        auto needed = bufferCount - mFramesAllowed;
-        LOG(INFO) << "Allocating " << needed << " buffers for camera frames";
-
-        auto added = increaseAvailableFrames_Locked(needed);
-        if (added != needed) {
-            // If we didn't add all the frames we needed, then roll back to the previous state
-            LOG(ERROR) << "Rolling back to previous frame queue size";
-            decreaseAvailableFrames_Locked(added);
-            return false;
-        }
-    } else if (mFramesAllowed > bufferCount) {
-        // A decrease is required
-        auto framesToRelease = mFramesAllowed - bufferCount;
-        LOG(INFO) << "Returning " << framesToRelease << " camera frame buffers";
-
-        auto released = decreaseAvailableFrames_Locked(framesToRelease);
-        if (released != framesToRelease) {
-            // This shouldn't happen with a properly behaving client because the client
-            // should only make this call after returning sufficient outstanding buffers
-            // to allow a clean resize.
-            LOG(ERROR) << "Buffer queue shrink failed -- too many buffers currently in use?";
-        }
-    }
-
-    return true;
-}
-
-unsigned EvsMockCamera::increaseAvailableFrames_Locked(unsigned numToAdd) {
-    // Acquire the graphics buffer allocator
-    ::android::GraphicBufferAllocator& alloc(::android::GraphicBufferAllocator::get());
-
-    unsigned added = 0;
-    while (added < numToAdd) {
-        unsigned pixelsPerLine = 0;
-        buffer_handle_t memHandle = nullptr;
-        auto result = alloc.allocate(mWidth, mHeight, mFormat, 1, mUsage, &memHandle,
-                                     &pixelsPerLine, 0, "EvsMockCamera");
-        if (result != ::android::NO_ERROR) {
-            LOG(ERROR) << "Error " << result << " allocating " << mWidth << " x " << mHeight
-                       << " graphics buffer";
-            break;
-        }
-        if (memHandle == nullptr) {
-            LOG(ERROR) << "We didn't get a buffer handle back from the allocator";
-            break;
-        }
-        if (mStride > 0) {
-            if (mStride != pixelsPerLine) {
-                LOG(ERROR) << "We did not expect to get buffers with different strides!";
-            }
-        } else {
-            // Gralloc defines stride in terms of pixels per line
-            mStride = pixelsPerLine;
-        }
-
-        // Find a place to store the new buffer
-        auto stored = false;
-        for (auto&& rec : mBuffers) {
-            if (rec.handle == nullptr) {
-                // Use this existing entry
-                rec.handle = memHandle;
-                rec.inUse = false;
-                stored = true;
-                break;
-            }
-        }
-        if (!stored) {
-            // Add a BufferRecord wrapping this handle to our set of available buffers
-            mBuffers.push_back(BufferRecord(memHandle));
-        }
-
-        ++mFramesAllowed;
-        ++added;
-    }
-
-    return added;
-}
-
-unsigned EvsMockCamera::decreaseAvailableFrames_Locked(unsigned numToRemove) {
-    // Acquire the graphics buffer allocator
-    ::android::GraphicBufferAllocator& alloc(::android::GraphicBufferAllocator::get());
-
-    unsigned removed = 0;
-    for (auto&& rec : mBuffers) {
-        // Is this record not in use, but holding a buffer that we can free?
-        if ((rec.inUse == false) && (rec.handle != nullptr)) {
-            // Release buffer and update the record so we can recognize it as "empty"
-            alloc.free(rec.handle);
-            rec.handle = nullptr;
-
-            --mFramesAllowed;
-            ++removed;
-
-            if (removed == numToRemove) {
-                break;
-            }
-        }
-    }
-
-    return removed;
-}
-
 // This is the asynchronous frame generation thread that runs in parallel with the
 // main serving thread.  There is one for each active camera instance.
 void EvsMockCamera::generateFrames() {
     LOG(DEBUG) << "Frame generation loop started.";
 
-    unsigned idx = 0;
     while (true) {
-        bool timeForFrame = false;
         const nsecs_t startTime = systemTime(SYSTEM_TIME_MONOTONIC);
-
-        // Lock scope for updating shared state
+        std::size_t bufferId = kInvalidBufferID;
+        buffer_handle_t bufferHandle = nullptr;
         {
-            std::lock_guard lock(mAccessLock);
-
-            if (mStreamState != RUNNING) {
-                // Break out of our main thread loop
+            std::lock_guard lock(mMutex);
+            if (mStreamState != StreamState::RUNNING) {
                 break;
             }
-
-            // Are we allowed to issue another buffer?
-            if (mFramesInUse >= mFramesAllowed) {
-                // Can't do anything right now -- skip this frame
-                LOG(WARNING) << "Skipped a frame because too many are in flight.";
-            } else {
-                // Identify an available buffer to fill
-                for (idx = 0; idx < mBuffers.size(); idx++) {
-                    if (!mBuffers[idx].inUse) {
-                        if (mBuffers[idx].handle != nullptr) {
-                            // Found an available record, so stop looking
-                            break;
-                        }
-                    }
-                }
-                if (idx >= mBuffers.size()) {
-                    // This shouldn't happen since we already checked mFramesInUse vs mFramesAllowed
-                    ALOGE("Failed to find an available buffer slot\n");
-                } else {
-                    // We're going to make the frame busy
-                    mBuffers[idx].inUse = true;
-                    mFramesInUse++;
-                    timeForFrame = true;
-                }
-            }
+            std::tie(bufferId, bufferHandle) = useBuffer_unsafe();
         }
 
-        if (timeForFrame) {
+        if (bufferHandle != nullptr) {
             using AidlPixelFormat = ::aidl::android::hardware::graphics::common::PixelFormat;
 
             // Assemble the buffer description we'll transmit below
-            buffer_handle_t memHandle = mBuffers[idx].handle;
             BufferDesc newBuffer = {
                     .buffer =
                             {
@@ -584,39 +225,31 @@
                                                     .usage = static_cast<BufferUsage>(mUsage),
                                                     .stride = static_cast<int32_t>(mStride),
                                             },
-                                    .handle = ::android::dupToAidl(memHandle),
+                                    .handle = ::android::dupToAidl(bufferHandle),
                             },
-                    .bufferId = static_cast<int32_t>(idx),
+                    .bufferId = static_cast<int32_t>(bufferId),
                     .deviceId = mDescription.id,
                     .timestamp = static_cast<int64_t>(::android::elapsedRealtimeNano() *
                                                       1e+3),  // timestamps is in microseconds
             };
 
             // Write test data into the image buffer
-            fillMockFrame(memHandle, reinterpret_cast<const AHardwareBuffer_Desc*>(
-                                             &newBuffer.buffer.description));
+            fillMockFrame(bufferHandle, reinterpret_cast<const AHardwareBuffer_Desc*>(
+                                                &newBuffer.buffer.description));
+
+            std::vector<BufferDesc> frames;
+            frames.push_back(std::move(newBuffer));
 
             // Issue the (asynchronous) callback to the client -- can't be holding the lock
-            auto flag = false;
-            if (mStream) {
-                std::vector<BufferDesc> frames;
-                frames.push_back(std::move(newBuffer));
-                flag = mStream->deliverFrame(frames).isOk();
-            }
-
-            if (flag) {
-                LOG(DEBUG) << "Delivered " << memHandle << ", id = " << mBuffers[idx].handle;
+            if (mStream && mStream->deliverFrame(frames).isOk()) {
+                LOG(DEBUG) << "Delivered " << bufferHandle << ", id = " << bufferId;
             } else {
                 // This can happen if the client dies and is likely unrecoverable.
                 // To avoid consuming resources generating failing calls, we stop sending
                 // frames.  Note, however, that the stream remains in the "STREAMING" state
                 // until cleaned up on the main thread.
                 LOG(ERROR) << "Frame delivery call failed in the transport layer.";
-
-                // Since we didn't actually deliver it, mark the frame as available
-                std::lock_guard<std::mutex> lock(mAccessLock);
-                mBuffers[idx].inUse = false;
-                mFramesInUse--;
+                doneWithFrame(frames);
             }
         }
 
@@ -671,34 +304,45 @@
     mapper.unlock(handle);
 }
 
-void EvsMockCamera::returnBufferLocked(const uint32_t bufferId) {
-    if (bufferId >= mBuffers.size()) {
-        ALOGE("ignoring doneWithFrame called with invalid bufferId %d (max is %zu)", bufferId,
-              mBuffers.size() - 1);
-        return;
+::android::status_t EvsMockCamera::allocateOneFrame(buffer_handle_t* handle) {
+    static auto& alloc = ::android::GraphicBufferAllocator::get();
+    unsigned pixelsPerLine = 0;
+    const auto result = alloc.allocate(mWidth, mHeight, mFormat, 1, mUsage, handle, &pixelsPerLine,
+                                       0, "EvsMockCamera");
+    if (mStride < mWidth) {
+        // Gralloc defines stride in terms of pixels per line
+        mStride = pixelsPerLine;
+    } else if (mStride != pixelsPerLine) {
+        LOG(ERROR) << "We did not expect to get buffers with different strides!";
     }
+    return result;
+}
 
-    if (!mBuffers[bufferId].inUse) {
-        ALOGE("ignoring doneWithFrame called on frame %d which is already free", bufferId);
-        return;
+bool EvsMockCamera::startVideoStreamImpl_locked(
+        const std::shared_ptr<evs::IEvsCameraStream>& receiver, ndk::ScopedAStatus& /* status */,
+        std::unique_lock<std::mutex>& /* lck */) {
+    mStream = receiver;
+    mCaptureThread = std::thread([this]() { generateFrames(); });
+    return true;
+}
+
+bool EvsMockCamera::stopVideoStreamImpl_locked(ndk::ScopedAStatus& /* status */,
+                                               std::unique_lock<std::mutex>& lck) {
+    lck.unlock();
+    if (mCaptureThread.joinable()) {
+        mCaptureThread.join();
     }
+    lck.lock();
+    return true;
+}
 
-    // Mark the frame as available
-    mBuffers[bufferId].inUse = false;
-    mFramesInUse--;
-
-    // If this frame's index is high in the array, try to move it down
-    // to improve locality after mFramesAllowed has been reduced.
-    if (bufferId >= mFramesAllowed) {
-        // Find an empty slot lower in the array (which should always exist in this case)
-        for (auto&& rec : mBuffers) {
-            if (rec.handle == nullptr) {
-                rec.handle = mBuffers[bufferId].handle;
-                mBuffers[bufferId].handle = nullptr;
-                break;
-            }
-        }
+bool EvsMockCamera::postVideoStreamStop_locked(ndk::ScopedAStatus& status,
+                                               std::unique_lock<std::mutex>& lck) {
+    if (!Base::postVideoStreamStop_locked(status, lck)) {
+        return false;
     }
+    mStream = nullptr;
+    return true;
 }
 
 std::shared_ptr<EvsMockCamera> EvsMockCamera::Create(const char* deviceName) {
diff --git a/automotive/evs/aidl/impl/default/src/EvsVideoEmulatedCamera.cpp b/automotive/evs/aidl/impl/default/src/EvsVideoEmulatedCamera.cpp
new file mode 100644
index 0000000..f198a64
--- /dev/null
+++ b/automotive/evs/aidl/impl/default/src/EvsVideoEmulatedCamera.cpp
@@ -0,0 +1,198 @@
+/*
+ * 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 "EvsVideoEmulatedCamera.h"
+
+#include <aidl/android/hardware/automotive/evs/EvsResult.h>
+
+#include <android-base/logging.h>
+
+#include <cstddef>
+#include <cstdint>
+
+namespace aidl::android::hardware::automotive::evs::implementation {
+
+EvsVideoEmulatedCamera::EvsVideoEmulatedCamera(Sigil, const char* deviceName,
+                                               std::unique_ptr<ConfigManager::CameraInfo>& camInfo)
+    : mCameraInfo(camInfo) {
+    mDescription.id = deviceName;
+
+    /* set camera metadata */
+    if (camInfo) {
+        uint8_t* ptr = reinterpret_cast<uint8_t*>(camInfo->characteristics);
+        const size_t len = get_camera_metadata_size(camInfo->characteristics);
+        mDescription.metadata.insert(mDescription.metadata.end(), ptr, ptr + len);
+    }
+
+    initializeParameters();
+}
+
+void EvsVideoEmulatedCamera::initializeParameters() {
+    mParams.emplace(
+            CameraParam::BRIGHTNESS,
+            new CameraParameterDesc(/* min= */ 0, /* max= */ 255, /* step= */ 1, /* value= */ 255));
+    mParams.emplace(
+            CameraParam::CONTRAST,
+            new CameraParameterDesc(/* min= */ 0, /* max= */ 255, /* step= */ 1, /* value= */ 255));
+    mParams.emplace(
+            CameraParam::SHARPNESS,
+            new CameraParameterDesc(/* min= */ 0, /* max= */ 255, /* step= */ 1, /* value= */ 255));
+}
+
+::android::status_t EvsVideoEmulatedCamera::allocateOneFrame(buffer_handle_t* /* handle */) {
+    LOG(FATAL) << __func__ << ": Not implemented yet.";
+    return ::android::UNKNOWN_ERROR;
+}
+
+bool EvsVideoEmulatedCamera::startVideoStreamImpl_locked(
+        const std::shared_ptr<evs::IEvsCameraStream>& /* receiver */,
+        ndk::ScopedAStatus& /* status */, std::unique_lock<std::mutex>& /* lck */) {
+    LOG(FATAL) << __func__ << ": Not implemented yet.";
+    return false;
+}
+
+bool EvsVideoEmulatedCamera::stopVideoStreamImpl_locked(ndk::ScopedAStatus& /* status */,
+                                                        std::unique_lock<std::mutex>& /* lck */) {
+    LOG(FATAL) << __func__ << ": Not implemented yet.";
+    return false;
+}
+
+ndk::ScopedAStatus EvsVideoEmulatedCamera::forcePrimaryClient(
+        const std::shared_ptr<evs::IEvsDisplay>& /* display */) {
+    /* Because EVS HW module reference implementation expects a single client at
+     * a time, this returns a success code always.
+     */
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus EvsVideoEmulatedCamera::getCameraInfo(evs::CameraDesc* _aidl_return) {
+    *_aidl_return = mDescription;
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus EvsVideoEmulatedCamera::getExtendedInfo(int32_t opaqueIdentifier,
+                                                           std::vector<uint8_t>* value) {
+    const auto it = mExtInfo.find(opaqueIdentifier);
+    if (it == mExtInfo.end()) {
+        return ndk::ScopedAStatus::fromServiceSpecificError(
+                static_cast<int>(EvsResult::INVALID_ARG));
+    } else {
+        *value = mExtInfo[opaqueIdentifier];
+    }
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus EvsVideoEmulatedCamera::getIntParameter(evs::CameraParam id,
+                                                           std::vector<int32_t>* value) {
+    const auto it = mParams.find(id);
+    if (it == mParams.end()) {
+        return ndk::ScopedAStatus::fromServiceSpecificError(
+                static_cast<int>(EvsResult::NOT_SUPPORTED));
+    }
+    value->push_back(it->second->value);
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus EvsVideoEmulatedCamera::getIntParameterRange(evs::CameraParam id,
+                                                                evs::ParameterRange* _aidl_return) {
+    const auto it = mParams.find(id);
+    if (it == mParams.end()) {
+        return ndk::ScopedAStatus::fromServiceSpecificError(
+                static_cast<int>(EvsResult::NOT_SUPPORTED));
+    }
+    _aidl_return->min = it->second->range.min;
+    _aidl_return->max = it->second->range.max;
+    _aidl_return->step = it->second->range.step;
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus EvsVideoEmulatedCamera::getParameterList(
+        std::vector<evs::CameraParam>* _aidl_return) {
+    if (mCameraInfo) {
+        _aidl_return->resize(mCameraInfo->controls.size());
+        std::size_t idx = 0;
+        for (const auto& [name, range] : mCameraInfo->controls) {
+            (*_aidl_return)[idx++] = name;
+        }
+    }
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus EvsVideoEmulatedCamera::getPhysicalCameraInfo(const std::string& /* deviceId */,
+                                                                 evs::CameraDesc* _aidl_return) {
+    return getCameraInfo(_aidl_return);
+}
+
+ndk::ScopedAStatus EvsVideoEmulatedCamera::setExtendedInfo(
+        int32_t opaqueIdentifier, const std::vector<uint8_t>& opaqueValue) {
+    mExtInfo.insert_or_assign(opaqueIdentifier, opaqueValue);
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus EvsVideoEmulatedCamera::setIntParameter(evs::CameraParam id, int32_t value,
+                                                           std::vector<int32_t>* effectiveValue) {
+    const auto it = mParams.find(id);
+    if (it == mParams.end()) {
+        return ndk::ScopedAStatus::fromServiceSpecificError(
+                static_cast<int>(EvsResult::NOT_SUPPORTED));
+    }
+    // Rounding down to the closest value.
+    int32_t candidate = value / it->second->range.step * it->second->range.step;
+    if (candidate < it->second->range.min || candidate > it->second->range.max) {
+        return ndk::ScopedAStatus::fromServiceSpecificError(
+                static_cast<int>(EvsResult::INVALID_ARG));
+    }
+    it->second->value = candidate;
+    effectiveValue->push_back(candidate);
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus EvsVideoEmulatedCamera::setPrimaryClient() {
+    /* Because EVS HW module reference implementation expects a single client at
+     * a time, this returns a success code always.
+     */
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus EvsVideoEmulatedCamera::unsetPrimaryClient() {
+    /* Because EVS HW module reference implementation expects a single client at
+     * a time, there is no chance that this is called by the secondary client and
+     * therefore returns a success code always.
+     */
+    return ndk::ScopedAStatus::ok();
+}
+
+std::shared_ptr<EvsVideoEmulatedCamera> EvsVideoEmulatedCamera::Create(const char* deviceName) {
+    std::unique_ptr<ConfigManager::CameraInfo> nullCamInfo = nullptr;
+    return Create(deviceName, nullCamInfo);
+}
+
+std::shared_ptr<EvsVideoEmulatedCamera> EvsVideoEmulatedCamera::Create(
+        const char* deviceName, std::unique_ptr<ConfigManager::CameraInfo>& camInfo,
+        const evs::Stream* /* streamCfg */) {
+    std::shared_ptr<EvsVideoEmulatedCamera> c =
+            ndk::SharedRefBase::make<EvsVideoEmulatedCamera>(Sigil{}, deviceName, camInfo);
+    if (!c) {
+        LOG(ERROR) << "Failed to instantiate EvsVideoEmulatedCamera.";
+        return nullptr;
+    }
+    c->mDescription.vendorFlags = 0xFFFFFFFF;  // Arbitrary test value
+    return c;
+}
+
+EvsVideoEmulatedCamera::~EvsVideoEmulatedCamera() {}
+
+}  // namespace aidl::android::hardware::automotive::evs::implementation
diff --git a/automotive/evs/aidl/impl/default/src/GlWrapper.cpp b/automotive/evs/aidl/impl/default/src/GlWrapper.cpp
index 0ee5ecb..a9d0213 100644
--- a/automotive/evs/aidl/impl/default/src/GlWrapper.cpp
+++ b/automotive/evs/aidl/impl/default/src/GlWrapper.cpp
@@ -19,6 +19,7 @@
 #include <aidl/android/frameworks/automotive/display/DisplayDesc.h>
 #include <aidl/android/hardware/graphics/common/HardwareBufferDescription.h>
 #include <aidlcommonsupport/NativeHandle.h>
+#include <gui/view/Surface.h>
 #include <ui/DisplayMode.h>
 #include <ui/DisplayState.h>
 #include <ui/GraphicBuffer.h>
@@ -183,20 +184,6 @@
     return program;
 }
 
-::android::sp<HGraphicBufferProducer> convertNativeHandleToHGBP(const NativeHandle& aidlHandle) {
-    native_handle_t* handle = ::android::dupFromAidl(aidlHandle);
-    if (handle->numFds != 0 || handle->numInts < std::ceil(sizeof(size_t) / sizeof(int))) {
-        LOG(ERROR) << "Invalid native handle";
-        return nullptr;
-    }
-    ::android::hardware::hidl_vec<uint8_t> halToken;
-    halToken.setToExternal(reinterpret_cast<uint8_t*>(const_cast<int*>(&(handle->data[1]))),
-                           handle->data[0]);
-    ::android::sp<HGraphicBufferProducer> hgbp =
-            HGraphicBufferProducer::castFrom(::android::retrieveHalInterface(halToken));
-    return std::move(hgbp);
-}
-
 }  // namespace
 
 namespace aidl::android::hardware::automotive::evs::implementation {
@@ -226,30 +213,19 @@
     }
     LOG(INFO) << "Display resolution is " << mWidth << "x" << mHeight;
 
-    NativeHandle aidlHandle;
-    status = pWindowProxy->getHGraphicBufferProducer(displayId, &aidlHandle);
+    aidl::android::view::Surface shimSurface;
+    status = pWindowProxy->getSurface(displayId, &shimSurface);
     if (!status.isOk()) {
-        LOG(ERROR) << "Failed to get IGraphicBufferProducer from ICarDisplayProxy.";
+        LOG(ERROR) << "Failed to obtain the surface.";
         return false;
     }
 
-    mGfxBufferProducer = convertNativeHandleToHGBP(aidlHandle);
-    if (!mGfxBufferProducer) {
-        LOG(ERROR) << "Failed to convert a NativeHandle to HGBP.";
-        return false;
-    }
-
-    mSurfaceHolder = getSurfaceFromHGBP(mGfxBufferProducer);
-    if (mSurfaceHolder == nullptr) {
-        LOG(ERROR) << "Failed to get a Surface from HGBP.";
-        return false;
-    }
-
-    mWindow = getNativeWindow(mSurfaceHolder.get());
+    mWindow = shimSurface.get();
     if (mWindow == nullptr) {
         LOG(ERROR) << "Failed to get a native window from Surface.";
         return false;
     }
+    ANativeWindow_acquire(mWindow);
 
     // Set up our OpenGL ES context associated with the default display
     mDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
@@ -350,7 +326,12 @@
     mDisplay = EGL_NO_DISPLAY;
 
     // Release the window
-    mSurfaceHolder = nullptr;
+    if (mWindow == nullptr) {
+        return;
+    }
+
+    ANativeWindow_release(mWindow);
+    mWindow = nullptr;
 }
 
 void GlWrapper::showWindow(const std::shared_ptr<ICarDisplayProxy>& pWindowProxy, uint64_t id) {
diff --git a/automotive/evs/aidl/impl/default/tests/EvsCameraBufferTest.cpp b/automotive/evs/aidl/impl/default/tests/EvsCameraBufferTest.cpp
new file mode 100644
index 0000000..8b4676e
--- /dev/null
+++ b/automotive/evs/aidl/impl/default/tests/EvsCameraBufferTest.cpp
@@ -0,0 +1,210 @@
+/*
+ * 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 "EvsCamera.h"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+#include <cstdint>
+#include <unordered_set>
+#include <vector>
+
+namespace aidl::android::hardware::automotive::evs::implementation {
+
+class EvsCameraForTest : public EvsCamera {
+  public:
+    using EvsCamera::increaseAvailableFrames_unsafe;
+    using EvsCamera::returnBuffer_unsafe;
+    using EvsCamera::useBuffer_unsafe;
+
+    ~EvsCameraForTest() override { shutdown(); }
+
+    ::android::status_t allocateOneFrame(buffer_handle_t* handle) override {
+        static std::intptr_t handle_cnt = 0;
+        *handle = reinterpret_cast<buffer_handle_t>(++handle_cnt);
+        return ::android::OK;
+    }
+
+    void freeOneFrame(const buffer_handle_t /* handle */) override {
+        // Nothing to free because the handles are fake.
+    }
+
+    void checkBufferOrder() {
+        for (std::size_t idx = 0; idx < mBuffers.size(); ++idx) {
+            const auto& buffer = mBuffers[idx];
+            EXPECT_EQ(idx < mFramesInUse, buffer.inUse);
+            EXPECT_EQ(idx < mAvailableFrames, buffer.handle != nullptr);
+            EXPECT_LE(mFramesInUse, mAvailableFrames);
+        }
+    }
+
+    MOCK_METHOD(::ndk::ScopedAStatus, forcePrimaryClient,
+                (const std::shared_ptr<::aidl::android::hardware::automotive::evs::IEvsDisplay>&
+                         in_display),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, getCameraInfo,
+                (::aidl::android::hardware::automotive::evs::CameraDesc * _aidl_return),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, getExtendedInfo,
+                (int32_t in_opaqueIdentifier, std::vector<uint8_t>* _aidl_return), (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, getIntParameter,
+                (::aidl::android::hardware::automotive::evs::CameraParam in_id,
+                 std::vector<int32_t>* _aidl_return),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, getIntParameterRange,
+                (::aidl::android::hardware::automotive::evs::CameraParam in_id,
+                 ::aidl::android::hardware::automotive::evs::ParameterRange* _aidl_return),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, getParameterList,
+                (std::vector<::aidl::android::hardware::automotive::evs::CameraParam> *
+                 _aidl_return),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, getPhysicalCameraInfo,
+                (const std::string& in_deviceId,
+                 ::aidl::android::hardware::automotive::evs::CameraDesc* _aidl_return),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, setExtendedInfo,
+                (int32_t in_opaqueIdentifier, const std::vector<uint8_t>& in_opaqueValue),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, setIntParameter,
+                (::aidl::android::hardware::automotive::evs::CameraParam in_id, int32_t in_value,
+                 std::vector<int32_t>* _aidl_return),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, setPrimaryClient, (), (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, unsetPrimaryClient, (), (override));
+    MOCK_METHOD(bool, startVideoStreamImpl_locked,
+                (const std::shared_ptr<evs::IEvsCameraStream>& receiver, ndk::ScopedAStatus& status,
+                 std::unique_lock<std::mutex>& lck),
+                (override));
+    MOCK_METHOD(bool, stopVideoStreamImpl_locked,
+                (ndk::ScopedAStatus & status, std::unique_lock<std::mutex>& lck), (override));
+};
+
+TEST(EvsCameraBufferTest, ChangeBufferPoolSize) {
+    auto evsCam = ndk::SharedRefBase::make<EvsCameraForTest>();
+    EXPECT_TRUE(evsCam->setMaxFramesInFlight(100).isOk());
+    evsCam->checkBufferOrder();
+    EXPECT_TRUE(evsCam->setMaxFramesInFlight(50).isOk());
+    evsCam->checkBufferOrder();
+
+    // 2 buffers in use.
+    const auto [id1, handle1] = evsCam->useBuffer_unsafe();
+    const auto [id2, handle2] = evsCam->useBuffer_unsafe();
+    std::ignore = evsCam->useBuffer_unsafe();
+
+    // It allows you to set the buffer pool size to 1, but it will keep the space for the in use
+    // buffers.
+    EXPECT_TRUE(evsCam->setMaxFramesInFlight(1).isOk());
+    evsCam->checkBufferOrder();
+
+    evsCam->returnBuffer_unsafe(id1);
+    evsCam->checkBufferOrder();
+    evsCam->returnBuffer_unsafe(id2);
+    evsCam->checkBufferOrder();
+}
+
+TEST(EvsCameraBufferTest, UseAndReturn) {
+    constexpr std::size_t kNumOfHandles = 20;
+    auto evsCam = ndk::SharedRefBase::make<EvsCameraForTest>();
+
+    // Our "fake handles" of this test case is 1 to kNumOfHandles.
+    for (std::size_t i = 1; i <= kNumOfHandles; ++i) {
+        evsCam->increaseAvailableFrames_unsafe(reinterpret_cast<buffer_handle_t>(i));
+    }
+    evsCam->checkBufferOrder();
+
+    {
+        std::vector<std::pair<std::size_t, std::intptr_t>> inUseIDHandlePairs;
+        std::unordered_set<std::size_t> inUseIDs;
+        std::unordered_set<std::intptr_t> inUseHandles;
+        for (std::size_t i = 0; i < kNumOfHandles; ++i) {
+            const auto [id, handle] = evsCam->useBuffer_unsafe();
+            const std::size_t handleInt = reinterpret_cast<std::size_t>(handle);
+            EXPECT_TRUE(EvsCamera::IsBufferIDValid(id));
+            EXPECT_NE(handle, nullptr);
+            EXPECT_LT(id, kNumOfHandles);
+
+            // handleInt must be between [1, kNumOfHandles] as we "allocated" above.
+            EXPECT_LT(0u, handleInt);
+            EXPECT_LE(handleInt, kNumOfHandles);
+
+            inUseIDHandlePairs.push_back({id, handleInt});
+            EXPECT_TRUE(inUseIDs.insert(id).second);
+            EXPECT_TRUE(inUseHandles.insert(handleInt).second);
+            evsCam->checkBufferOrder();
+        }
+        // Return buffers in the order of acquiring.
+        for (const auto [id, handleInt] : inUseIDHandlePairs) {
+            evsCam->returnBuffer_unsafe(id);
+            evsCam->checkBufferOrder();
+        }
+    }
+
+    {
+        std::vector<std::pair<std::size_t, std::intptr_t>> inUseIDHandlePairs;
+        std::unordered_set<std::size_t> inUseIDs;
+        std::unordered_set<std::intptr_t> inUseHandles;
+        for (std::size_t i = 0; i < kNumOfHandles; ++i) {
+            const auto [id, handle] = evsCam->useBuffer_unsafe();
+            const std::size_t handleInt = reinterpret_cast<std::size_t>(handle);
+            EXPECT_TRUE(EvsCamera::IsBufferIDValid(id));
+            EXPECT_NE(handle, nullptr);
+            EXPECT_LT(id, kNumOfHandles);
+
+            // handleInt must be between [1, kNumOfHandles] as we "allocated" above.
+            EXPECT_LT(0u, handleInt);
+            EXPECT_LE(handleInt, kNumOfHandles);
+
+            inUseIDHandlePairs.push_back({id, handleInt});
+            EXPECT_TRUE(inUseIDs.insert(id).second);
+            EXPECT_TRUE(inUseHandles.insert(handleInt).second);
+            evsCam->checkBufferOrder();
+        }
+        // Return buffers in the reverse order of acquiring.
+        std::reverse(inUseIDHandlePairs.begin(), inUseIDHandlePairs.end());
+        for (const auto [id, handleInt] : inUseIDHandlePairs) {
+            evsCam->returnBuffer_unsafe(id);
+            evsCam->checkBufferOrder();
+        }
+    }
+
+    {
+        // Making sure the handles are still in [1, kNumOfHandles] and IDs are still [0,
+        // kNumOfHandles). The mapping may be different, though.
+        std::vector<std::pair<std::size_t, std::intptr_t>> inUseIDHandlePairs;
+        std::unordered_set<std::size_t> inUseIDs;
+        std::unordered_set<std::intptr_t> inUseHandles;
+        for (std::size_t i = 0; i < kNumOfHandles; ++i) {
+            const auto [id, handle] = evsCam->useBuffer_unsafe();
+            const std::size_t handleInt = reinterpret_cast<std::size_t>(handle);
+            EXPECT_TRUE(EvsCamera::IsBufferIDValid(id));
+            EXPECT_NE(handle, nullptr);
+            EXPECT_LT(id, kNumOfHandles);
+
+            // handleInt must be between [1, kNumOfHandles] as we "allocated" above.
+            EXPECT_LT(0u, handleInt);
+            EXPECT_LE(handleInt, kNumOfHandles);
+
+            inUseIDHandlePairs.push_back({id, handleInt});
+            EXPECT_TRUE(inUseIDs.insert(id).second);
+            EXPECT_TRUE(inUseHandles.insert(handleInt).second);
+            evsCam->checkBufferOrder();
+        }
+    }
+}
+
+}  // namespace aidl::android::hardware::automotive::evs::implementation
diff --git a/automotive/evs/aidl/impl/default/tests/EvsCameraStateTest.cpp b/automotive/evs/aidl/impl/default/tests/EvsCameraStateTest.cpp
new file mode 100644
index 0000000..1925c79
--- /dev/null
+++ b/automotive/evs/aidl/impl/default/tests/EvsCameraStateTest.cpp
@@ -0,0 +1,202 @@
+/*
+ * 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 "EvsCamera.h"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+#include <cstdint>
+#include <unordered_set>
+#include <vector>
+
+namespace aidl::android::hardware::automotive::evs::implementation {
+
+class EvsCameraForTest : public EvsCamera {
+  private:
+    using Base = EvsCamera;
+
+  public:
+    using EvsCamera::mStreamState;
+    using EvsCamera::shutdown;
+    using EvsCamera::StreamState;
+
+    ~EvsCameraForTest() override { shutdown(); }
+
+    ::android::status_t allocateOneFrame(buffer_handle_t* handle) override {
+        static std::intptr_t handle_cnt = 0;
+        *handle = reinterpret_cast<buffer_handle_t>(++handle_cnt);
+        return ::android::OK;
+    }
+
+    void freeOneFrame(const buffer_handle_t /* handle */) override {
+        // Nothing to free because the handles are fake.
+    }
+
+    bool preVideoStreamStart_locked(const std::shared_ptr<evs::IEvsCameraStream>& receiver,
+                                    ndk::ScopedAStatus& status,
+                                    std::unique_lock<std::mutex>& lck) override {
+        mPreStartCalled = true;
+        EXPECT_EQ(mStreamState, StreamState::STOPPED);
+        EXPECT_FALSE(mStreamStarted);
+        EXPECT_FALSE(mStreamStopped);
+        return Base::preVideoStreamStart_locked(receiver, status, lck);
+    }
+
+    bool startVideoStreamImpl_locked(const std::shared_ptr<evs::IEvsCameraStream>& /* receiver */,
+                                     ndk::ScopedAStatus& /* status */,
+                                     std::unique_lock<std::mutex>& /* lck */) override {
+        EXPECT_EQ(mStreamState, StreamState::RUNNING);
+        EXPECT_FALSE(mStreamStarted);
+        EXPECT_FALSE(mStreamStopped);
+        mStreamStarted = true;
+        return true;
+    }
+
+    bool postVideoStreamStart_locked(const std::shared_ptr<evs::IEvsCameraStream>& receiver,
+                                     ndk::ScopedAStatus& status,
+                                     std::unique_lock<std::mutex>& lck) override {
+        mPostStartCalled = true;
+        EXPECT_EQ(mStreamState, StreamState::RUNNING);
+        EXPECT_TRUE(mStreamStarted);
+        EXPECT_FALSE(mStreamStopped);
+        return Base::postVideoStreamStart_locked(receiver, status, lck);
+    }
+
+    bool preVideoStreamStop_locked(ndk::ScopedAStatus& status,
+                                   std::unique_lock<std::mutex>& lck) override {
+        // Skip the check if stop was called before.
+        if (!mPreStopCalled) {
+            mPreStopCalled = true;
+            EXPECT_EQ(mStreamState, StreamState::RUNNING);
+            EXPECT_TRUE(mStreamStarted);
+            EXPECT_FALSE(mStreamStopped);
+        }
+        return Base::preVideoStreamStop_locked(status, lck);
+    }
+
+    bool stopVideoStreamImpl_locked(ndk::ScopedAStatus& /* status */,
+                                    std::unique_lock<std::mutex>& /* lck */) override {
+        EXPECT_EQ(mStreamState, StreamState::STOPPING);
+        EXPECT_TRUE(mStreamStarted);
+        EXPECT_FALSE(mStreamStopped);
+        mStreamStopped = true;
+        return true;
+    }
+
+    bool postVideoStreamStop_locked(ndk::ScopedAStatus& status,
+                                    std::unique_lock<std::mutex>& lck) override {
+        mPostStopCalled = true;
+        const auto ret = Base::postVideoStreamStop_locked(status, lck);
+        EXPECT_EQ(mStreamState, StreamState::STOPPED);
+        EXPECT_TRUE(mStreamStarted);
+        EXPECT_TRUE(mStreamStopped);
+        return ret;
+    }
+
+    MOCK_METHOD(::ndk::ScopedAStatus, forcePrimaryClient,
+                (const std::shared_ptr<::aidl::android::hardware::automotive::evs::IEvsDisplay>&
+                         in_display),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, getCameraInfo,
+                (::aidl::android::hardware::automotive::evs::CameraDesc * _aidl_return),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, getExtendedInfo,
+                (int32_t in_opaqueIdentifier, std::vector<uint8_t>* _aidl_return), (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, getIntParameter,
+                (::aidl::android::hardware::automotive::evs::CameraParam in_id,
+                 std::vector<int32_t>* _aidl_return),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, getIntParameterRange,
+                (::aidl::android::hardware::automotive::evs::CameraParam in_id,
+                 ::aidl::android::hardware::automotive::evs::ParameterRange* _aidl_return),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, getParameterList,
+                (std::vector<::aidl::android::hardware::automotive::evs::CameraParam> *
+                 _aidl_return),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, getPhysicalCameraInfo,
+                (const std::string& in_deviceId,
+                 ::aidl::android::hardware::automotive::evs::CameraDesc* _aidl_return),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, setExtendedInfo,
+                (int32_t in_opaqueIdentifier, const std::vector<uint8_t>& in_opaqueValue),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, setIntParameter,
+                (::aidl::android::hardware::automotive::evs::CameraParam in_id, int32_t in_value,
+                 std::vector<int32_t>* _aidl_return),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, setPrimaryClient, (), (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, unsetPrimaryClient, (), (override));
+
+    bool mStreamStarted = false;
+    bool mStreamStopped = false;
+    bool mPreStartCalled = false;
+    bool mPostStartCalled = false;
+    bool mPreStopCalled = false;
+    bool mPostStopCalled = false;
+};
+
+class MockEvsCameraStream : public evs::IEvsCameraStream {
+    MOCK_METHOD(::ndk::SpAIBinder, asBinder, (), (override));
+    MOCK_METHOD(bool, isRemote, (), (override));
+    MOCK_METHOD(
+            ::ndk::ScopedAStatus, deliverFrame,
+            (const std::vector<::aidl::android::hardware::automotive::evs::BufferDesc>& in_buffer),
+            (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, notify,
+                (const ::aidl::android::hardware::automotive::evs::EvsEventDesc& in_event),
+                (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, getInterfaceVersion, (int32_t * _aidl_return), (override));
+    MOCK_METHOD(::ndk::ScopedAStatus, getInterfaceHash, (std::string * _aidl_return), (override));
+};
+
+using StreamState = EvsCameraForTest::StreamState;
+
+TEST(EvsCameraStateTest, StateChangeHooks) {
+    auto evsCam = ndk::SharedRefBase::make<EvsCameraForTest>();
+    auto mockStream = ndk::SharedRefBase::make<MockEvsCameraStream>();
+    EXPECT_FALSE(evsCam->mPreStartCalled);
+    EXPECT_FALSE(evsCam->mPostStartCalled);
+    EXPECT_FALSE(evsCam->mPreStopCalled);
+    EXPECT_FALSE(evsCam->mPostStopCalled);
+    EXPECT_FALSE(evsCam->mStreamStarted);
+    EXPECT_FALSE(evsCam->mStreamStopped);
+    EXPECT_EQ(evsCam->mStreamState, StreamState::STOPPED);
+    evsCam->startVideoStream(mockStream);
+
+    EXPECT_TRUE(evsCam->mPreStartCalled);
+    EXPECT_TRUE(evsCam->mPostStartCalled);
+    EXPECT_FALSE(evsCam->mPreStopCalled);
+    EXPECT_FALSE(evsCam->mPostStopCalled);
+    EXPECT_TRUE(evsCam->mStreamStarted);
+    EXPECT_FALSE(evsCam->mStreamStopped);
+    EXPECT_EQ(evsCam->mStreamState, StreamState::RUNNING);
+    evsCam->stopVideoStream();
+
+    EXPECT_TRUE(evsCam->mPreStartCalled);
+    EXPECT_TRUE(evsCam->mPostStartCalled);
+    EXPECT_TRUE(evsCam->mPreStopCalled);
+    EXPECT_TRUE(evsCam->mPostStopCalled);
+    EXPECT_TRUE(evsCam->mStreamStarted);
+    EXPECT_TRUE(evsCam->mStreamStopped);
+    EXPECT_EQ(evsCam->mStreamState, StreamState::STOPPED);
+
+    evsCam->shutdown();
+    EXPECT_EQ(evsCam->mStreamState, StreamState::DEAD);
+}
+
+}  // namespace aidl::android::hardware::automotive::evs::implementation
diff --git a/automotive/remoteaccess/Android.bp b/automotive/remoteaccess/Android.bp
index 7cd6f60..e1e9041 100644
--- a/automotive/remoteaccess/Android.bp
+++ b/automotive/remoteaccess/Android.bp
@@ -42,6 +42,5 @@
             imports: [],
         },
     ],
-    frozen: true,
-
+    frozen: false,
 }
diff --git a/automotive/remoteaccess/aidl_api/android.hardware.automotive.remoteaccess/current/android/hardware/automotive/remoteaccess/IRemoteAccess.aidl b/automotive/remoteaccess/aidl_api/android.hardware.automotive.remoteaccess/current/android/hardware/automotive/remoteaccess/IRemoteAccess.aidl
index b0935c2..ccfa22d 100644
--- a/automotive/remoteaccess/aidl_api/android.hardware.automotive.remoteaccess/current/android/hardware/automotive/remoteaccess/IRemoteAccess.aidl
+++ b/automotive/remoteaccess/aidl_api/android.hardware.automotive.remoteaccess/current/android/hardware/automotive/remoteaccess/IRemoteAccess.aidl
@@ -40,4 +40,10 @@
   void setRemoteTaskCallback(android.hardware.automotive.remoteaccess.IRemoteTaskCallback callback);
   void clearRemoteTaskCallback();
   void notifyApStateChange(in android.hardware.automotive.remoteaccess.ApState state);
+  boolean isTaskScheduleSupported();
+  void scheduleTask(in android.hardware.automotive.remoteaccess.ScheduleInfo scheduleInfo);
+  void unscheduleTask(String clientId, String scheduleId);
+  void unscheduleAllTasks(String clientId);
+  boolean isTaskScheduled(String clientId, String scheduleId);
+  List<android.hardware.automotive.remoteaccess.ScheduleInfo> getAllScheduledTasks(String clientId);
 }
diff --git a/automotive/remoteaccess/aidl_api/android.hardware.automotive.remoteaccess/current/android/hardware/automotive/remoteaccess/ScheduleInfo.aidl b/automotive/remoteaccess/aidl_api/android.hardware.automotive.remoteaccess/current/android/hardware/automotive/remoteaccess/ScheduleInfo.aidl
new file mode 100644
index 0000000..a929e10
--- /dev/null
+++ b/automotive/remoteaccess/aidl_api/android.hardware.automotive.remoteaccess/current/android/hardware/automotive/remoteaccess/ScheduleInfo.aidl
@@ -0,0 +1,43 @@
+/*
+ * 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.automotive.remoteaccess;
+@JavaDerive(equals=true, toString=true) @VintfStability
+parcelable ScheduleInfo {
+  String clientId;
+  String scheduleId;
+  byte[] taskData;
+  int count;
+  long startTimeInEpochSeconds;
+  long periodicInSeconds;
+}
diff --git a/automotive/remoteaccess/android/hardware/automotive/remoteaccess/IRemoteAccess.aidl b/automotive/remoteaccess/android/hardware/automotive/remoteaccess/IRemoteAccess.aidl
index 0f4125f..4912651 100644
--- a/automotive/remoteaccess/android/hardware/automotive/remoteaccess/IRemoteAccess.aidl
+++ b/automotive/remoteaccess/android/hardware/automotive/remoteaccess/IRemoteAccess.aidl
@@ -18,6 +18,7 @@
 
 import android.hardware.automotive.remoteaccess.ApState;
 import android.hardware.automotive.remoteaccess.IRemoteTaskCallback;
+import android.hardware.automotive.remoteaccess.ScheduleInfo;
 
 /**
  * Interface representing a remote wakeup client.
@@ -96,4 +97,69 @@
      * <p>If {@code isWakeupRequired} is false, it must not try to wake up AP.
      */
     void notifyApStateChange(in ApState state);
+
+    /**
+     * Returns whether task scheduling is supported.
+     *
+     * <p>If this returns {@code true}, user may use {@link scheduleTask} to schedule a task to be
+     * executed at a later time. If the device is off when the task is scheduled to be executed,
+     * the device will be woken up to execute the task.
+     *
+     * @return {@code true} if serverless remote task scheduling is supported.
+     */
+    boolean isTaskScheduleSupported();
+
+    /**
+     * Schedules a task to be executed later even when the vehicle is off.
+     *
+     * <p>If {@link isTaskScheduleSupported} returns {@code false}. This is no-op.
+     *
+     * <p>This sends a scheduled task message to a device external to Android so that the device
+     * can wake up Android and deliver the task through {@link IRemoteTaskCallback}.
+     *
+     * <p>Note that the scheduled task execution is on a best-effort basis. Multiple situations
+     * might cause the task not to execute successfully:
+     *
+     * <ul>
+     * <li>The vehicle is low on battery and the other device decides not to wake up Android.
+     * <li>User turns off vehicle while the task is executing.
+     * <li>The task logic itself fails.
+     *
+     * <p>Must return {@code EX_ILLEGAL_ARGUMENT} if a pending schedule with the same
+     * {@code scheduleId} for this client exists.
+     */
+    void scheduleTask(in ScheduleInfo scheduleInfo);
+
+    /**
+     * Unschedules a scheduled task.
+     *
+     * <p>If {@link isTaskScheduleSupported} returns {@code false}. This is no-op.
+     *
+     * <p>Does nothing if a pending schedule with {@code clientId} and {@code scheduleId} does not
+     * exist.
+     */
+    void unscheduleTask(String clientId, String scheduleId);
+
+    /**
+     * Unschedules all scheduled tasks for the client.
+     *
+     * <p>If {@link isTaskScheduleSupported} returns {@code false}. This is no-op.
+     */
+    void unscheduleAllTasks(String clientId);
+
+    /**
+     * Returns whether the specified task is scheduled.
+     *
+     * <p>If {@link isTaskScheduleSupported} returns {@code false}, This must return {@code false}.
+     */
+    boolean isTaskScheduled(String clientId, String scheduleId);
+
+    /**
+     * Gets all pending scheduled tasks for the client.
+     *
+     * <p>If {@link isTaskScheduleSupported} returns {@code false}. This must return empty array.
+     *
+     * <p>The finished scheduled tasks will not be included.
+     */
+    List<ScheduleInfo> getAllScheduledTasks(String clientId);
 }
diff --git a/automotive/remoteaccess/android/hardware/automotive/remoteaccess/ScheduleInfo.aidl b/automotive/remoteaccess/android/hardware/automotive/remoteaccess/ScheduleInfo.aidl
new file mode 100644
index 0000000..cf1437b
--- /dev/null
+++ b/automotive/remoteaccess/android/hardware/automotive/remoteaccess/ScheduleInfo.aidl
@@ -0,0 +1,62 @@
+/*
+ * 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.automotive.remoteaccess;
+
+@VintfStability
+@JavaDerive(equals=true, toString=true)
+parcelable ScheduleInfo {
+    /**
+     * The ID used to identify the client this schedule is for. This must be one of the
+     * preconfigured remote access serverless client ID defined in car service resource
+     * {@code R.xml.remote_access_serverless_client_map}.
+     */
+    String clientId;
+    /**
+     * A unique scheduling ID (among the same client). Adding a new schedule info with a duplicate
+     * scheduleId will return {@code EX_ILLEGAL_ARGUMENT}.
+     */
+    String scheduleId;
+    /**
+     * The opaque task data that will be sent back to the remote task client app when the task is
+     * executed. It is not interpreted/parsed by the Android system.
+     */
+    byte[] taskData;
+    /**
+     * How many times this task will be executed. 0 means infinite.
+     *
+     * <p>This must be >= 0.
+     */
+    int count;
+    /**
+     * The start time in epoch seconds.
+     *
+     * <p>The external device issuing remote task must have a clock synced with the
+     * {@code System.currentTimeMillis()} used in Android system.
+     *
+     * <p>Optionally, the VHAL property {@code EPOCH_TIME} can be used to sync the time.
+     *
+     * <p>This must be >= 0.
+     */
+    long startTimeInEpochSeconds;
+    /**
+     * The interval (in seconds) between scheduled task execution.
+     *
+     * <p>This must be >=0. This is not useful when {@code count} is 1. If this is 0,
+     * The tasks will be delivered multiple times with no interval in between.
+     */
+    long periodicInSeconds;
+}
diff --git a/automotive/remoteaccess/hal/default/Android.bp b/automotive/remoteaccess/hal/default/Android.bp
index 48a7309..97ed2c1 100644
--- a/automotive/remoteaccess/hal/default/Android.bp
+++ b/automotive/remoteaccess/hal/default/Android.bp
@@ -48,7 +48,7 @@
 }
 
 cc_binary {
-    name: "android.hardware.automotive.remoteaccess@V1-default-service",
+    name: "android.hardware.automotive.remoteaccess@V2-default-service",
     defaults: ["remote-access-hal-defaults"],
     vintf_fragments: ["remoteaccess-default-service.xml"],
     init_rc: ["remoteaccess-default-service.rc"],
@@ -58,7 +58,7 @@
 }
 
 cc_binary {
-    name: "android.hardware.automotive.remoteaccess@V1-tcu-test-service",
+    name: "android.hardware.automotive.remoteaccess@V2-tcu-test-service",
     defaults: ["remote-access-hal-defaults"],
     vintf_fragments: ["remoteaccess-default-service.xml"],
     init_rc: ["remoteaccess-tcu-test-service.rc"],
@@ -77,7 +77,7 @@
         "src/RemoteAccessService.cpp",
     ],
     whole_static_libs: [
-        "android.hardware.automotive.remoteaccess-V1-ndk",
+        "android.hardware.automotive.remoteaccess-V2-ndk",
         "wakeup_client_protos",
         "libvhalclient",
     ],
@@ -99,7 +99,7 @@
 }
 
 cc_fuzz {
-    name: "android.hardware.automotive.remoteaccess@V1-default-service.aidl_fuzzer",
+    name: "android.hardware.automotive.remoteaccess@V2-default-service.aidl_fuzzer",
     srcs: ["fuzzer/fuzzer.cpp"],
     whole_static_libs: [
         "RemoteAccessService",
diff --git a/automotive/remoteaccess/hal/default/include/RemoteAccessService.h b/automotive/remoteaccess/hal/default/include/RemoteAccessService.h
index b18986a..1fc4037 100644
--- a/automotive/remoteaccess/hal/default/include/RemoteAccessService.h
+++ b/automotive/remoteaccess/hal/default/include/RemoteAccessService.h
@@ -21,6 +21,7 @@
 #include <aidl/android/hardware/automotive/remoteaccess/BnRemoteAccess.h>
 #include <aidl/android/hardware/automotive/remoteaccess/BnRemoteTaskCallback.h>
 #include <aidl/android/hardware/automotive/remoteaccess/IRemoteTaskCallback.h>
+#include <aidl/android/hardware/automotive/remoteaccess/ScheduleInfo.h>
 #include <android-base/thread_annotations.h>
 #include <android/binder_auto_utils.h>
 #include <utils/SystemClock.h>
@@ -78,6 +79,25 @@
     ndk::ScopedAStatus notifyApStateChange(
             const aidl::android::hardware::automotive::remoteaccess::ApState& newState) override;
 
+    ndk::ScopedAStatus isTaskScheduleSupported(bool* out) override;
+
+    ndk::ScopedAStatus scheduleTask(
+            const aidl::android::hardware::automotive::remoteaccess::ScheduleInfo& scheduleInfo)
+            override;
+
+    ndk::ScopedAStatus unscheduleTask(const std::string& clientId,
+                                      const std::string& scheduleId) override;
+
+    ndk::ScopedAStatus unscheduleAllTasks(const std::string& clientId) override;
+
+    ndk::ScopedAStatus isTaskScheduled(const std::string& clientId, const std::string& scheduleId,
+                                       bool* out) override;
+
+    ndk::ScopedAStatus getAllScheduledTasks(
+            const std::string& clientId,
+            std::vector<aidl::android::hardware::automotive::remoteaccess::ScheduleInfo>* out)
+            override;
+
     binder_status_t dump(int fd, const char** args, uint32_t numArgs) override;
 
   private:
diff --git a/automotive/remoteaccess/hal/default/remoteaccess-default-service.rc b/automotive/remoteaccess/hal/default/remoteaccess-default-service.rc
index b7a9cdc..c9b282c 100644
--- a/automotive/remoteaccess/hal/default/remoteaccess-default-service.rc
+++ b/automotive/remoteaccess/hal/default/remoteaccess-default-service.rc
@@ -1,4 +1,4 @@
-service vendor.remoteaccess-default /vendor/bin/hw/android.hardware.automotive.remoteaccess@V1-default-service
+service vendor.remoteaccess-default /vendor/bin/hw/android.hardware.automotive.remoteaccess@V2-default-service
     class hal
     user vehicle_network
     group system inet
diff --git a/automotive/remoteaccess/hal/default/remoteaccess-default-service.xml b/automotive/remoteaccess/hal/default/remoteaccess-default-service.xml
index d050a1b..44ac309 100644
--- a/automotive/remoteaccess/hal/default/remoteaccess-default-service.xml
+++ b/automotive/remoteaccess/hal/default/remoteaccess-default-service.xml
@@ -1,7 +1,7 @@
 <manifest version="1.0" type="device">
     <hal format="aidl">
         <name>android.hardware.automotive.remoteaccess</name>
-        <version>1</version>
+        <version>2</version>
         <fqname>IRemoteAccess/default</fqname>
     </hal>
 </manifest>
diff --git a/automotive/remoteaccess/hal/default/remoteaccess-tcu-test-service.rc b/automotive/remoteaccess/hal/default/remoteaccess-tcu-test-service.rc
index 59315eb..19faaf4 100644
--- a/automotive/remoteaccess/hal/default/remoteaccess-tcu-test-service.rc
+++ b/automotive/remoteaccess/hal/default/remoteaccess-tcu-test-service.rc
@@ -1,4 +1,4 @@
-service vendor.remoteaccess-default /vendor/bin/hw/android.hardware.automotive.remoteaccess@V1-tcu-test-service
+service vendor.remoteaccess-default /vendor/bin/hw/android.hardware.automotive.remoteaccess@V2-tcu-test-service
     class hal
     user vehicle_network
     group system inet
diff --git a/automotive/remoteaccess/hal/default/src/RemoteAccessService.cpp b/automotive/remoteaccess/hal/default/src/RemoteAccessService.cpp
index 5081ac0..7721bf4 100644
--- a/automotive/remoteaccess/hal/default/src/RemoteAccessService.cpp
+++ b/automotive/remoteaccess/hal/default/src/RemoteAccessService.cpp
@@ -39,6 +39,7 @@
 
 using ::aidl::android::hardware::automotive::remoteaccess::ApState;
 using ::aidl::android::hardware::automotive::remoteaccess::IRemoteTaskCallback;
+using ::aidl::android::hardware::automotive::remoteaccess::ScheduleInfo;
 using ::aidl::android::hardware::automotive::vehicle::VehicleProperty;
 using ::android::base::Error;
 using ::android::base::ParseInt;
@@ -313,6 +314,41 @@
     return ScopedAStatus::ok();
 }
 
+ScopedAStatus RemoteAccessService::isTaskScheduleSupported([[maybe_unused]] bool* out) {
+    // TODO(b/297271235): implement this.
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus RemoteAccessService::scheduleTask([[maybe_unused]] const ScheduleInfo& scheduleInfo) {
+    // TODO(b/297271235): implement this.
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus RemoteAccessService::unscheduleTask([[maybe_unused]] const std::string& clientId,
+                                                  [[maybe_unused]] const std::string& scheduleId) {
+    // TODO(b/297271235): implement this.
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus RemoteAccessService::unscheduleAllTasks(
+        [[maybe_unused]] const std::string& clientId) {
+    // TODO(b/297271235): implement this.
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus RemoteAccessService::isTaskScheduled([[maybe_unused]] const std::string& clientId,
+                                                   [[maybe_unused]] const std::string& scheduleId,
+                                                   [[maybe_unused]] bool* out) {
+    // TODO(b/297271235): implement this.
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus RemoteAccessService::getAllScheduledTasks(const std::string& clientId,
+                                                        std::vector<ScheduleInfo>* out) {
+    // TODO(b/297271235): implement this.
+    return ScopedAStatus::ok();
+}
+
 bool RemoteAccessService::checkDumpPermission() {
     uid_t uid = AIBinder_getCallingUid();
     return uid == AID_ROOT || uid == AID_SHELL || uid == AID_SYSTEM;
diff --git a/automotive/remoteaccess/test_grpc_server/README.md b/automotive/remoteaccess/test_grpc_server/README.md
index af3d54a..d2b6bbe 100644
--- a/automotive/remoteaccess/test_grpc_server/README.md
+++ b/automotive/remoteaccess/test_grpc_server/README.md
@@ -141,7 +141,7 @@
 * The android lunch target: sdk_car_x86_64-userdebug and
   cf_x86_64_auto-userdebug already contains the default remote access HAL. For
   other lunch target, you can add the default remote access HAL by adding
-  'android.hardware.automotive.remoteaccess@V1-default-service' to
+  'android.hardware.automotive.remoteaccess@V2-default-service' to
   'PRODUCT_PACKAGES' variable in mk file, see `device/generic/car/common/car.mk`
   as example.
 
diff --git a/automotive/sv/1.0/default/tests/fuzzer/AutomotiveSvV1_0Fuzzer.cpp b/automotive/sv/1.0/default/tests/fuzzer/AutomotiveSvV1_0Fuzzer.cpp
index 98834f5..4c4cc70 100644
--- a/automotive/sv/1.0/default/tests/fuzzer/AutomotiveSvV1_0Fuzzer.cpp
+++ b/automotive/sv/1.0/default/tests/fuzzer/AutomotiveSvV1_0Fuzzer.cpp
@@ -41,35 +41,32 @@
 
 void SurroundViewFuzzer::invoke2dSessionAPI() {
     sp<ISurroundView2dSession> surroundView2dSession;
+    sp<SurroundViewStream> handler;
+    mSurroundViewService->start2dSession(
+            [&surroundView2dSession](const sp<ISurroundView2dSession>& session, SvResult result) {
+                if (result == SvResult::OK) {
+                    surroundView2dSession = session;
+                }
+            });
+
+    if (surroundView2dSession && !mIs2dStreamStarted) {
+        handler = sp<SurroundViewStream>::make(surroundView2dSession);
+        if (surroundView2dSession->startStream(handler) == SvResult::OK) {
+            mIs2dStreamStarted = true;
+        }
+    }
 
     while (mFuzzedDataProvider.remaining_bytes() > 0) {
         auto surroundView2dFunc = mFuzzedDataProvider.PickValueInArray<
                 const std::function<void()>>({
                 [&]() {
-                    mSurroundViewService->start2dSession(
-                            [&surroundView2dSession](const sp<ISurroundView2dSession>& session,
-                                                     SvResult result) {
-                                if (result == SvResult::OK) {
-                                    surroundView2dSession = session;
-                                }
-                            });
-                },
-                [&]() {
-                    if (surroundView2dSession) {
-                        sp<SurroundViewStream> handler =
-                                sp<SurroundViewStream>::make(surroundView2dSession);
-                        surroundView2dSession->startStream(handler);
-                        mIs2dStreamStarted = true;
-                    }
-                },
-                [&]() {
                     if (surroundView2dSession) {
                         surroundView2dSession->get2dMappingInfo(
                                 []([[maybe_unused]] Sv2dMappingInfo info) {});
                     }
                 },
                 [&]() {
-                    if (surroundView2dSession) {
+                    if (surroundView2dSession && mIs2dStreamStarted) {
                         Sv2dConfig config;
                         config.width = mFuzzedDataProvider.ConsumeIntegralInRange<uint32_t>(
                                 kMinConfigDimension, kMaxConfigDimension);
@@ -149,8 +146,11 @@
                     }
                 },
                 [&]() {
-                    mSurroundViewService->stop2dSession(
+                    SvResult result = mSurroundViewService->stop2dSession(
                             mFuzzedDataProvider.ConsumeBool() ? surroundView2dSession : nullptr);
+                    if (result == SvResult::OK) {
+                        mIs2dStreamStarted = false;
+                    }
                 },
         });
         surroundView2dFunc();
@@ -159,31 +159,40 @@
     if (surroundView2dSession && mIs2dStreamStarted) {
         surroundView2dSession->stopStream();
     }
+
+    if (surroundView2dSession) {
+        mSurroundViewService->stop2dSession(surroundView2dSession);
+    }
 }
 
 void SurroundViewFuzzer::invoke3dSessionAPI() {
     sp<ISurroundView3dSession> surroundView3dSession;
+    sp<SurroundViewStream> handler;
+    mSurroundViewService->start3dSession(
+            [&surroundView3dSession](const sp<ISurroundView3dSession>& session, SvResult result) {
+                if (result == SvResult::OK) {
+                    surroundView3dSession = session;
+                }
+            });
+
+    const size_t numViews = mFuzzedDataProvider.ConsumeIntegralInRange<size_t>(1, kMaxViews);
+    std::vector<View3d> views(numViews);
+    for (size_t i = 0; i < numViews; ++i) {
+        views[i].viewId = mFuzzedDataProvider.ConsumeIntegral<uint32_t>();
+    }
+    surroundView3dSession->setViews(views);
+
+    if (surroundView3dSession) {
+        handler = sp<SurroundViewStream>::make(surroundView3dSession);
+
+        if (surroundView3dSession->startStream(handler) == SvResult::OK) {
+            mIs3dStreamStarted = true;
+        }
+    }
     while (mFuzzedDataProvider.remaining_bytes() > 0) {
         auto surroundView3dFunc = mFuzzedDataProvider.PickValueInArray<
                 const std::function<void()>>({
                 [&]() {
-                    mSurroundViewService->start3dSession(
-                            [&surroundView3dSession](const sp<ISurroundView3dSession>& session,
-                                                     SvResult result) {
-                                if (result == SvResult::OK) {
-                                    surroundView3dSession = session;
-                                }
-                            });
-                },
-                [&]() {
-                    if (surroundView3dSession) {
-                        sp<SurroundViewStream> handler =
-                                sp<SurroundViewStream>::make(surroundView3dSession);
-                        surroundView3dSession->startStream(handler);
-                        mIs3dStreamStarted = true;
-                    }
-                },
-                [&]() {
                     if (surroundView3dSession) {
                         const size_t numViews =
                                 mFuzzedDataProvider.ConsumeIntegralInRange<size_t>(1, kMaxViews);
@@ -195,7 +204,7 @@
                     }
                 },
                 [&]() {
-                    if (surroundView3dSession) {
+                    if (surroundView3dSession && mIs3dStreamStarted) {
                         Sv3dConfig config;
                         config.width = mFuzzedDataProvider.ConsumeIntegralInRange<uint32_t>(
                                 kMinConfigDimension, kMaxConfigDimension);
@@ -306,8 +315,11 @@
                     }
                 },
                 [&]() {
-                    mSurroundViewService->stop3dSession(
+                    SvResult result = mSurroundViewService->stop3dSession(
                             mFuzzedDataProvider.ConsumeBool() ? surroundView3dSession : nullptr);
+                    if (result == SvResult::OK) {
+                        mIs3dStreamStarted = false;
+                    }
                 },
         });
         surroundView3dFunc();
@@ -315,6 +327,10 @@
     if (surroundView3dSession && mIs3dStreamStarted) {
         surroundView3dSession->stopStream();
     }
+
+    if (surroundView3dSession) {
+        mSurroundViewService->stop3dSession(surroundView3dSession);
+    }
 }
 
 void SurroundViewFuzzer::process() {
diff --git a/automotive/vehicle/2.0/default/tests/fuzzer/VehicleManager_fuzzer.cpp b/automotive/vehicle/2.0/default/tests/fuzzer/VehicleManager_fuzzer.cpp
index 796c08f..8a085e5 100644
--- a/automotive/vehicle/2.0/default/tests/fuzzer/VehicleManager_fuzzer.cpp
+++ b/automotive/vehicle/2.0/default/tests/fuzzer/VehicleManager_fuzzer.cpp
@@ -161,10 +161,13 @@
     hidl_string debugOption = mFuzzedDataProvider->PickValueInArray(
             {"--help", "--list", "--get", "--set", "", "invalid"});
     hidl_handle fd = {};
-    fd.setTo(native_handle_create(/*numFds=*/1, /*numInts=*/0), /*shouldOwn=*/true);
+
+    native_handle_t* rawHandle = native_handle_create(/*numFds=*/1, /*numInts=*/0);
+    fd.setTo(native_handle_clone(rawHandle), /*shouldOwn=*/true);
 
     mManager->debug(fd, {});
     mManager->debug(fd, {debugOption});
+    native_handle_delete(rawHandle);
 }
 
 void VehicleHalManagerFuzzer::invokePropConfigs() {
diff --git a/automotive/vehicle/OWNERS b/automotive/vehicle/OWNERS
index 429ec39..d6969e5 100644
--- a/automotive/vehicle/OWNERS
+++ b/automotive/vehicle/OWNERS
@@ -1,3 +1,2 @@
 ericjeong@google.com
-keunyoung@google.com
 shanyu@google.com
diff --git a/automotive/vehicle/aidl/aidl_test/Android.bp b/automotive/vehicle/aidl/aidl_test/Android.bp
index 79ac309..b8f797f 100644
--- a/automotive/vehicle/aidl/aidl_test/Android.bp
+++ b/automotive/vehicle/aidl/aidl_test/Android.bp
@@ -54,7 +54,7 @@
         "android.hardware.automotive.vehicle-V2-java",
         "android.hardware.automotive.vehicle.property-V3-java",
         "androidx.test.runner",
-        "truth-prebuilt",
+        "truth",
     ],
     test_suites: ["general-tests"],
 }
diff --git a/automotive/vehicle/aidl/generated_lib/cpp/AccessForVehicleProperty.h b/automotive/vehicle/aidl/generated_lib/cpp/AccessForVehicleProperty.h
index 7c07e49..c4e2c64 100644
--- a/automotive/vehicle/aidl/generated_lib/cpp/AccessForVehicleProperty.h
+++ b/automotive/vehicle/aidl/generated_lib/cpp/AccessForVehicleProperty.h
@@ -247,6 +247,7 @@
         {VehicleProperty::SUPPORTED_PROPERTY_IDS, VehiclePropertyAccess::READ},
         {VehicleProperty::SHUTDOWN_REQUEST, VehiclePropertyAccess::WRITE},
         {VehicleProperty::VEHICLE_IN_USE, VehiclePropertyAccess::READ_WRITE},
+        {VehicleProperty::CLUSTER_HEARTBEAT, VehiclePropertyAccess::WRITE},
         {VehicleProperty::AUTOMATIC_EMERGENCY_BRAKING_ENABLED, VehiclePropertyAccess::READ_WRITE},
         {VehicleProperty::AUTOMATIC_EMERGENCY_BRAKING_STATE, VehiclePropertyAccess::READ},
         {VehicleProperty::FORWARD_COLLISION_WARNING_ENABLED, VehiclePropertyAccess::READ_WRITE},
diff --git a/automotive/vehicle/aidl/generated_lib/cpp/ChangeModeForVehicleProperty.h b/automotive/vehicle/aidl/generated_lib/cpp/ChangeModeForVehicleProperty.h
index fec2f06..bd6c705 100644
--- a/automotive/vehicle/aidl/generated_lib/cpp/ChangeModeForVehicleProperty.h
+++ b/automotive/vehicle/aidl/generated_lib/cpp/ChangeModeForVehicleProperty.h
@@ -247,6 +247,7 @@
         {VehicleProperty::SUPPORTED_PROPERTY_IDS, VehiclePropertyChangeMode::STATIC},
         {VehicleProperty::SHUTDOWN_REQUEST, VehiclePropertyChangeMode::ON_CHANGE},
         {VehicleProperty::VEHICLE_IN_USE, VehiclePropertyChangeMode::ON_CHANGE},
+        {VehicleProperty::CLUSTER_HEARTBEAT, VehiclePropertyChangeMode::ON_CHANGE},
         {VehicleProperty::AUTOMATIC_EMERGENCY_BRAKING_ENABLED, VehiclePropertyChangeMode::ON_CHANGE},
         {VehicleProperty::AUTOMATIC_EMERGENCY_BRAKING_STATE, VehiclePropertyChangeMode::ON_CHANGE},
         {VehicleProperty::FORWARD_COLLISION_WARNING_ENABLED, VehiclePropertyChangeMode::ON_CHANGE},
diff --git a/automotive/vehicle/aidl/generated_lib/java/AccessForVehicleProperty.java b/automotive/vehicle/aidl/generated_lib/java/AccessForVehicleProperty.java
index 91af12d..6e66632 100644
--- a/automotive/vehicle/aidl/generated_lib/java/AccessForVehicleProperty.java
+++ b/automotive/vehicle/aidl/generated_lib/java/AccessForVehicleProperty.java
@@ -239,6 +239,7 @@
         Map.entry(VehicleProperty.SUPPORTED_PROPERTY_IDS, VehiclePropertyAccess.READ),
         Map.entry(VehicleProperty.SHUTDOWN_REQUEST, VehiclePropertyAccess.WRITE),
         Map.entry(VehicleProperty.VEHICLE_IN_USE, VehiclePropertyAccess.READ_WRITE),
+        Map.entry(VehicleProperty.CLUSTER_HEARTBEAT, VehiclePropertyAccess.WRITE),
         Map.entry(VehicleProperty.AUTOMATIC_EMERGENCY_BRAKING_ENABLED, VehiclePropertyAccess.READ_WRITE),
         Map.entry(VehicleProperty.AUTOMATIC_EMERGENCY_BRAKING_STATE, VehiclePropertyAccess.READ),
         Map.entry(VehicleProperty.FORWARD_COLLISION_WARNING_ENABLED, VehiclePropertyAccess.READ_WRITE),
diff --git a/automotive/vehicle/aidl/generated_lib/java/ChangeModeForVehicleProperty.java b/automotive/vehicle/aidl/generated_lib/java/ChangeModeForVehicleProperty.java
index 32e71c0..522c82f 100644
--- a/automotive/vehicle/aidl/generated_lib/java/ChangeModeForVehicleProperty.java
+++ b/automotive/vehicle/aidl/generated_lib/java/ChangeModeForVehicleProperty.java
@@ -239,6 +239,7 @@
         Map.entry(VehicleProperty.SUPPORTED_PROPERTY_IDS, VehiclePropertyChangeMode.STATIC),
         Map.entry(VehicleProperty.SHUTDOWN_REQUEST, VehiclePropertyChangeMode.ON_CHANGE),
         Map.entry(VehicleProperty.VEHICLE_IN_USE, VehiclePropertyChangeMode.ON_CHANGE),
+        Map.entry(VehicleProperty.CLUSTER_HEARTBEAT, VehiclePropertyChangeMode.ON_CHANGE),
         Map.entry(VehicleProperty.AUTOMATIC_EMERGENCY_BRAKING_ENABLED, VehiclePropertyChangeMode.ON_CHANGE),
         Map.entry(VehicleProperty.AUTOMATIC_EMERGENCY_BRAKING_STATE, VehiclePropertyChangeMode.ON_CHANGE),
         Map.entry(VehicleProperty.FORWARD_COLLISION_WARNING_ENABLED, VehiclePropertyChangeMode.ON_CHANGE),
diff --git a/automotive/vehicle/aidl/impl/README.md b/automotive/vehicle/aidl/impl/README.md
index 121ffd1..2cd3a3e 100644
--- a/automotive/vehicle/aidl/impl/README.md
+++ b/automotive/vehicle/aidl/impl/README.md
@@ -46,7 +46,7 @@
 use this library, along with their own implementation for `IVehicleHardware`
 interface.
 
-Also defines a binary `android.hardware.automotive.vehicle@V1-default-service`
+Also defines a binary `android.hardware.automotive.vehicle@V3-default-service`
 which is the reference VHAL implementation. It implements `IVehicle.aidl`
 interface. It uses `DefaultVehicleHal`, along with `FakeVehicleHardware`
 (in fake_impl). It simulates the vehicle bus interaction by using an
diff --git a/automotive/vehicle/aidl/impl/default_config/config/DefaultProperties.json b/automotive/vehicle/aidl/impl/default_config/config/DefaultProperties.json
index b9f784b..6c8d59c 100644
--- a/automotive/vehicle/aidl/impl/default_config/config/DefaultProperties.json
+++ b/automotive/vehicle/aidl/impl/default_config/config/DefaultProperties.json
@@ -1899,8 +1899,16 @@
                 }
             ],
             "configArray": [
+                "VehicleProperty::HVAC_ACTUAL_FAN_SPEED_RPM",
+                "VehicleProperty::HVAC_AC_ON",
+                "VehicleProperty::HVAC_AUTO_ON",
+                "VehicleProperty::HVAC_AUTO_RECIRC_ON",
+                "VehicleProperty::HVAC_FAN_DIRECTION",
                 "VehicleProperty::HVAC_FAN_SPEED",
-                "VehicleProperty::HVAC_FAN_DIRECTION"
+                "VehicleProperty::HVAC_MAX_AC_ON",
+                "VehicleProperty::HVAC_RECIRC_ON",
+                "VehicleProperty::HVAC_TEMPERATURE_CURRENT",
+                "VehicleProperty::HVAC_TEMPERATURE_SET"
             ]
         },
         {
@@ -3621,6 +3629,21 @@
             "property": "VehicleProperty::CLUSTER_NAVIGATION_STATE"
         },
         {
+            "property": "VehicleProperty::CLUSTER_HEARTBEAT",
+            "configArray": [
+                0,
+                0,
+                0,
+                0,
+                0,
+                2,
+                0,
+                0,
+                16
+            ],
+            "comment": "configArray specifies it consists of int64[2] and byte[16]."
+        },
+        {
             "property": "VehicleProperty::GENERAL_SAFETY_REGULATION_COMPLIANCE_REQUIREMENT",
             "defaultValue": {
                 "int32Values": [
diff --git a/automotive/vehicle/aidl/impl/fake_impl/hardware/include/FakeVehicleHardware.h b/automotive/vehicle/aidl/impl/fake_impl/hardware/include/FakeVehicleHardware.h
index f130fa4..844bea5 100644
--- a/automotive/vehicle/aidl/impl/fake_impl/hardware/include/FakeVehicleHardware.h
+++ b/automotive/vehicle/aidl/impl/fake_impl/hardware/include/FakeVehicleHardware.h
@@ -36,6 +36,7 @@
 #include <memory>
 #include <mutex>
 #include <unordered_map>
+#include <unordered_set>
 #include <vector>
 
 namespace android {
@@ -99,12 +100,17 @@
     const std::shared_ptr<VehiclePropValuePool> mValuePool;
     const std::shared_ptr<VehiclePropertyStore> mServerSidePropStore;
 
+    const std::string mDefaultConfigDir;
+    const std::string mOverrideConfigDir;
+
     ValueResultType getValue(
             const aidl::android::hardware::automotive::vehicle::VehiclePropValue& value) const;
 
     VhalResult<void> setValue(
             const aidl::android::hardware::automotive::vehicle::VehiclePropValue& value);
 
+    bool UseOverrideConfigDir();
+
   private:
     // Expose private methods to unit test.
     friend class FakeVehicleHardwareTestHelper;
@@ -156,8 +162,9 @@
                                   aidl::android::hardware::automotive::vehicle::SetValueRequest>
             mPendingSetValueRequests;
 
-    const std::string mDefaultConfigDir;
-    const std::string mOverrideConfigDir;
+    // Set of HVAC properties dependent on HVAC_POWER_ON
+    std::unordered_set<int32_t> hvacPowerDependentProps;
+
     const bool mForceOverride;
     bool mAddExtraTestVendorConfigs;
 
@@ -250,7 +257,7 @@
             const aidl::android::hardware::automotive::vehicle::SetValueRequest& request);
 
     std::string genFakeDataCommand(const std::vector<std::string>& options);
-    void sendHvacPropertiesCurrentValues(int32_t areaId);
+    void sendHvacPropertiesCurrentValues(int32_t areaId, int32_t hvacPowerOnVal);
     void sendAdasPropertiesState(int32_t propertyId, int32_t state);
     void generateVendorConfigs(
             std::vector<aidl::android::hardware::automotive::vehicle::VehiclePropConfig>&) const;
diff --git a/automotive/vehicle/aidl/impl/fake_impl/hardware/src/FakeVehicleHardware.cpp b/automotive/vehicle/aidl/impl/fake_impl/hardware/src/FakeVehicleHardware.cpp
index 82c3ea0..ee24fbd 100644
--- a/automotive/vehicle/aidl/impl/fake_impl/hardware/src/FakeVehicleHardware.cpp
+++ b/automotive/vehicle/aidl/impl/fake_impl/hardware/src/FakeVehicleHardware.cpp
@@ -39,7 +39,6 @@
 #include <dirent.h>
 #include <inttypes.h>
 #include <sys/types.h>
-#include <fstream>
 #include <regex>
 #include <unordered_set>
 #include <vector>
@@ -201,14 +200,20 @@
     bool globalProp = isGlobalProp(propId);
     size_t numAreas = globalProp ? 1 : vehiclePropConfig.areaConfigs.size();
 
+    if (propId == toInt(VehicleProperty::HVAC_POWER_ON)) {
+        const auto& configArray = vehiclePropConfig.configArray;
+        hvacPowerDependentProps.insert(configArray.begin(), configArray.end());
+    }
+
     for (size_t i = 0; i < numAreas; i++) {
         int32_t curArea = globalProp ? 0 : vehiclePropConfig.areaConfigs[i].areaId;
 
         // Create a separate instance for each individual zone
         VehiclePropValue prop = {
+                .timestamp = elapsedRealtimeNano(),
                 .areaId = curArea,
                 .prop = propId,
-                .timestamp = elapsedRealtimeNano(),
+                .value = {},
         };
 
         if (config.initialAreaValues.empty()) {
@@ -241,6 +246,8 @@
                                          std::string overrideConfigDir, bool forceOverride)
     : mValuePool(std::make_unique<VehiclePropValuePool>()),
       mServerSidePropStore(new VehiclePropertyStore(mValuePool)),
+      mDefaultConfigDir(defaultConfigDir),
+      mOverrideConfigDir(overrideConfigDir),
       mFakeObd2Frame(new obd2frame::FakeObd2Frame(mServerSidePropStore)),
       mFakeUserHal(new FakeUserHal(mValuePool)),
       mRecurrentTimer(new RecurrentTimer()),
@@ -248,8 +255,6 @@
               [this](const VehiclePropValue& value) { eventFromVehicleBus(value); })),
       mPendingGetValueRequests(this),
       mPendingSetValueRequests(this),
-      mDefaultConfigDir(defaultConfigDir),
-      mOverrideConfigDir(overrideConfigDir),
       mForceOverride(forceOverride) {
     init();
 }
@@ -260,11 +265,15 @@
     mGeneratorHub.reset();
 }
 
+bool FakeVehicleHardware::UseOverrideConfigDir() {
+    return mForceOverride ||
+           android::base::GetBoolProperty(OVERRIDE_PROPERTY, /*default_value=*/false);
+}
+
 std::unordered_map<int32_t, ConfigDeclaration> FakeVehicleHardware::loadConfigDeclarations() {
     std::unordered_map<int32_t, ConfigDeclaration> configsByPropId;
     loadPropConfigsFromDir(mDefaultConfigDir, &configsByPropId);
-    if (mForceOverride ||
-        android::base::GetBoolProperty(OVERRIDE_PROPERTY, /*default_value=*/false)) {
+    if (UseOverrideConfigDir()) {
         loadPropConfigsFromDir(mOverrideConfigDir, &configsByPropId);
     }
     return configsByPropId;
@@ -507,9 +516,7 @@
 }
 
 bool FakeVehicleHardware::isHvacPropAndHvacNotAvailable(int32_t propId, int32_t areaId) const {
-    std::unordered_set<int32_t> powerProps(std::begin(HVAC_POWER_PROPERTIES),
-                                           std::end(HVAC_POWER_PROPERTIES));
-    if (powerProps.count(propId)) {
+    if (hvacPowerDependentProps.count(propId)) {
         auto hvacPowerOnResults =
                 mServerSidePropStore->readValuesForProperty(toInt(VehicleProperty::HVAC_POWER_ON));
         if (!hvacPowerOnResults.ok()) {
@@ -727,9 +734,8 @@
     return std::move(gotValue);
 }
 
-void FakeVehicleHardware::sendHvacPropertiesCurrentValues(int32_t areaId) {
-    for (size_t i = 0; i < sizeof(HVAC_POWER_PROPERTIES) / sizeof(int32_t); i++) {
-        int powerPropId = HVAC_POWER_PROPERTIES[i];
+void FakeVehicleHardware::sendHvacPropertiesCurrentValues(int32_t areaId, int32_t hvacPowerOnVal) {
+    for (auto& powerPropId : hvacPowerDependentProps) {
         auto powerPropResults = mServerSidePropStore->readValuesForProperty(powerPropId);
         if (!powerPropResults.ok()) {
             ALOGW("failed to get power prop 0x%x, error: %s", powerPropId,
@@ -740,7 +746,8 @@
         for (size_t j = 0; j < powerPropValues.size(); j++) {
             auto powerPropValue = std::move(powerPropValues[j]);
             if ((powerPropValue->areaId & areaId) == powerPropValue->areaId) {
-                powerPropValue->status = VehiclePropertyStatus::AVAILABLE;
+                powerPropValue->status = hvacPowerOnVal ? VehiclePropertyStatus::AVAILABLE
+                                                        : VehiclePropertyStatus::UNAVAILABLE;
                 powerPropValue->timestamp = elapsedRealtimeNano();
                 // This will trigger a property change event for the current hvac property value.
                 mServerSidePropStore->writeValue(std::move(powerPropValue), /*updateStatus=*/true,
@@ -792,13 +799,6 @@
         return setUserHalProp(value);
     }
 
-    if (propId == toInt(VehicleProperty::HVAC_POWER_ON) && value.value.int32Values.size() == 1 &&
-        value.value.int32Values[0] == 1) {
-        // If we are turning HVAC power on, send current hvac property values through on change
-        // event.
-        sendHvacPropertiesCurrentValues(value.areaId);
-    }
-
     if (isHvacPropAndHvacNotAvailable(propId, value.areaId)) {
         *isSpecialValue = true;
         return StatusError(StatusCode::NOT_AVAILABLE_DISABLED) << "hvac not available";
@@ -837,6 +837,16 @@
         case toInt(TestVendorProperty::VENDOR_PROPERTY_FOR_ERROR_CODE_TESTING):
             *isSpecialValue = true;
             return StatusError((StatusCode)VENDOR_ERROR_CODE);
+        case toInt(VehicleProperty::HVAC_POWER_ON):
+            if (value.value.int32Values.size() != 1) {
+                *isSpecialValue = true;
+                return StatusError(StatusCode::INVALID_ARG)
+                       << "HVAC_POWER_ON requires only one int32 value";
+            }
+            // When changing HVAC power state, send current hvac property values
+            // through on change event.
+            sendHvacPropertiesCurrentValues(value.areaId, value.value.int32Values[0]);
+            return {};
         case toInt(VehicleProperty::HVAC_TEMPERATURE_VALUE_SUGGESTION):
             *isSpecialValue = true;
             return setHvacTemperatureValueSuggestion(value);
@@ -1035,7 +1045,7 @@
                    << StringPrintf("failed to get special value: %d, error: %s", value.prop,
                                    getErrorMsg(result).c_str());
         } else {
-            return std::move(result);
+            return result;
         }
     }
 
@@ -1050,7 +1060,7 @@
         }
     }
 
-    return std::move(readResult);
+    return readResult;
 }
 
 DumpResult FakeVehicleHardware::dump(const std::vector<std::string>& options) {
@@ -1087,9 +1097,11 @@
     } else if (EqualsIgnoreCase(option, "--genTestVendorConfigs")) {
         mAddExtraTestVendorConfigs = true;
         result.refreshPropertyConfigs = true;
+        result.buffer = "successfully generated vendor configs";
     } else if (EqualsIgnoreCase(option, "--restoreVendorConfigs")) {
         mAddExtraTestVendorConfigs = false;
         result.refreshPropertyConfigs = true;
+        result.buffer = "successfully restored vendor configs";
     } else {
         result.buffer = StringPrintf("Invalid option: %s\n", option.c_str());
     }
@@ -1425,9 +1437,9 @@
 VehiclePropValue FakeVehicleHardware::createHwInputKeyProp(VehicleHwKeyInputAction action,
                                                            int32_t keyCode, int32_t targetDisplay) {
     VehiclePropValue value = {
-            .prop = toInt(VehicleProperty::HW_KEY_INPUT),
-            .areaId = 0,
             .timestamp = elapsedRealtimeNano(),
+            .areaId = 0,
+            .prop = toInt(VehicleProperty::HW_KEY_INPUT),
             .status = VehiclePropertyStatus::AVAILABLE,
             .value.int32Values = {toInt(action), keyCode, targetDisplay},
     };
@@ -1437,9 +1449,9 @@
 VehiclePropValue FakeVehicleHardware::createHwKeyInputV2Prop(int32_t area, int32_t targetDisplay,
                                                              int32_t keyCode, int32_t action,
                                                              int32_t repeatCount) {
-    VehiclePropValue value = {.prop = toInt(VehicleProperty::HW_KEY_INPUT_V2),
+    VehiclePropValue value = {.timestamp = elapsedRealtimeNano(),
                               .areaId = area,
-                              .timestamp = elapsedRealtimeNano(),
+                              .prop = toInt(VehicleProperty::HW_KEY_INPUT_V2),
                               .status = VehiclePropertyStatus::AVAILABLE,
                               .value.int32Values = {targetDisplay, keyCode, action, repeatCount},
                               .value.int64Values = {elapsedRealtimeNano()}};
@@ -1477,9 +1489,9 @@
         floatValues.push_back(size[i]);
     }
 
-    VehiclePropValue value = {.prop = toInt(VehicleProperty::HW_MOTION_INPUT),
+    VehiclePropValue value = {.timestamp = elapsedRealtimeNano(),
                               .areaId = area,
-                              .timestamp = elapsedRealtimeNano(),
+                              .prop = toInt(VehicleProperty::HW_MOTION_INPUT),
                               .status = VehiclePropertyStatus::AVAILABLE,
                               .value.int32Values = intValues,
                               .value.floatValues = floatValues,
@@ -1548,8 +1560,9 @@
 
 std::string FakeVehicleHardware::dumpOnePropertyById(int32_t propId, int32_t areaId) {
     VehiclePropValue value = {
-            .prop = propId,
             .areaId = areaId,
+            .prop = propId,
+            .value = {},
     };
     bool isSpecialValue = false;
     auto result = maybeGetSpecialValue(value, &isSpecialValue);
@@ -1620,12 +1633,12 @@
     while (*index < options.size()) {
         std::string option = options[*index];
         if (SET_PROP_OPTIONS.find(option) != SET_PROP_OPTIONS.end()) {
-            return std::move(values);
+            return values;
         }
         values.push_back(option);
         (*index)++;
     }
-    return std::move(values);
+    return values;
 }
 
 Result<VehiclePropValue> FakeVehicleHardware::parsePropOptions(
@@ -1934,8 +1947,9 @@
         // Refresh the property value. In real implementation, this should poll the latest value
         // from vehicle bus. Here, we are just refreshing the existing value with a new timestamp.
         auto result = getValue(VehiclePropValue{
-                .prop = propId,
                 .areaId = areaId,
+                .prop = propId,
+                .value = {},
         });
         if (!result.ok()) {
             // Failed to read current value, skip refreshing.
diff --git a/automotive/vehicle/aidl/impl/fake_impl/hardware/test/FakeVehicleHardwareTest.cpp b/automotive/vehicle/aidl/impl/fake_impl/hardware/test/FakeVehicleHardwareTest.cpp
index 6cc06bc..cf9beee 100644
--- a/automotive/vehicle/aidl/impl/fake_impl/hardware/test/FakeVehicleHardwareTest.cpp
+++ b/automotive/vehicle/aidl/impl/fake_impl/hardware/test/FakeVehicleHardwareTest.cpp
@@ -35,6 +35,7 @@
 #include <inttypes.h>
 #include <chrono>
 #include <condition_variable>
+#include <memory>
 #include <unordered_map>
 #include <unordered_set>
 #include <vector>
@@ -78,7 +79,9 @@
 using ::aidl::android::hardware::automotive::vehicle::VehicleHwKeyInputAction;
 using ::aidl::android::hardware::automotive::vehicle::VehiclePropConfig;
 using ::aidl::android::hardware::automotive::vehicle::VehicleProperty;
+using ::aidl::android::hardware::automotive::vehicle::VehiclePropertyAccess;
 using ::aidl::android::hardware::automotive::vehicle::VehiclePropertyStatus;
+using ::aidl::android::hardware::automotive::vehicle::VehiclePropertyType;
 using ::aidl::android::hardware::automotive::vehicle::VehiclePropValue;
 using ::aidl::android::hardware::automotive::vehicle::VehicleUnit;
 using ::android::base::expected;
@@ -109,6 +112,10 @@
         return mHardware->loadConfigDeclarations();
     }
 
+    std::unordered_set<int32_t> getHvacPowerDependentProps() {
+        return mHardware->hvacPowerDependentProps;
+    }
+
   private:
     FakeVehicleHardware* mHardware;
 };
@@ -390,6 +397,25 @@
         }
     } mPropValueCmp;
 
+    std::unique_ptr<VehiclePropConfig> getVehiclePropConfig(int32_t propertyId) {
+        auto configs = mHardware->getAllPropertyConfigs();
+        for (auto& config : configs) {
+            if (config.prop == propertyId) {
+                auto ptr = std::make_unique<VehiclePropConfig>();
+                ptr->prop = config.prop;
+                ptr->access = config.access;
+                ptr->changeMode = config.changeMode;
+                ptr->areaConfigs = config.areaConfigs;
+                ptr->configArray = config.configArray;
+                ptr->configString = config.configString;
+                ptr->minSampleRate = config.minSampleRate;
+                ptr->maxSampleRate = config.maxSampleRate;
+                return ptr;
+            }
+        }
+        return std::unique_ptr<VehiclePropConfig>(nullptr);
+    }
+
   private:
     std::unique_ptr<FakeVehicleHardware> mHardware;
     std::shared_ptr<IVehicleHardware::SetValuesCallback> mSetValuesCallback;
@@ -1687,23 +1713,35 @@
 }
 
 TEST_F(FakeVehicleHardwareTest, testGetHvacPropNotAvailable) {
-    int seatAreaIds[5] = {SEAT_1_LEFT, SEAT_1_RIGHT, SEAT_2_LEFT, SEAT_2_CENTER, SEAT_2_RIGHT};
-    for (int areaId : seatAreaIds) {
+    FakeVehicleHardwareTestHelper helper(getHardware());
+    auto hvacPowerOnConfig = std::move(getVehiclePropConfig(toInt(VehicleProperty::HVAC_POWER_ON)));
+    EXPECT_NE(hvacPowerOnConfig, nullptr);
+    for (auto& hvacPowerOnAreaConfig : hvacPowerOnConfig->areaConfigs) {
+        int hvacPowerAreaId = hvacPowerOnAreaConfig.areaId;
+        // Turn off HVAC_POWER_ON for only 1 area ID
         StatusCode status = setValue(VehiclePropValue{.prop = toInt(VehicleProperty::HVAC_POWER_ON),
-                                                      .areaId = areaId,
+                                                      .areaId = hvacPowerAreaId,
                                                       .value.int32Values = {0}});
+        EXPECT_EQ(status, StatusCode::OK);
 
-        ASSERT_EQ(status, StatusCode::OK);
-
-        for (size_t i = 0; i < sizeof(HVAC_POWER_PROPERTIES) / sizeof(int32_t); i++) {
-            int powerPropId = HVAC_POWER_PROPERTIES[i];
-            for (int powerDependentAreaId : seatAreaIds) {
+        for (auto& powerPropId : helper.getHvacPowerDependentProps()) {
+            auto powerPropConfig = std::move(getVehiclePropConfig(powerPropId));
+            EXPECT_NE(powerPropConfig, nullptr);
+            if (powerPropConfig->access == VehiclePropertyAccess::WRITE) {
+                continue;
+            }
+            // Try getting a value at each area ID supported by the power dependent property
+            for (auto& powerPropAreaConfig : powerPropConfig->areaConfigs) {
+                int powerDependentAreaId = powerPropAreaConfig.areaId;
                 auto getValueResult = getValue(VehiclePropValue{
                         .prop = powerPropId,
                         .areaId = powerDependentAreaId,
                 });
 
-                if (areaId == powerDependentAreaId) {
+                // If the current area ID is contained within the HVAC_POWER_ON area ID
+                // turned off, then getValue should fail and a StatusCode error should be
+                // returned. Otherwise, a value should be returned.
+                if ((hvacPowerAreaId & powerDependentAreaId) == powerDependentAreaId) {
                     EXPECT_FALSE(getValueResult.ok());
                     EXPECT_EQ(getValueResult.error(), StatusCode::NOT_AVAILABLE_DISABLED);
                 } else {
@@ -1716,28 +1754,45 @@
         // on this value from any power dependent property values other than those with the same
         // areaId.
         setValue(VehiclePropValue{.prop = toInt(VehicleProperty::HVAC_POWER_ON),
-                                  .areaId = areaId,
+                                  .areaId = hvacPowerAreaId,
                                   .value.int32Values = {1}});
     }
 }
 
 TEST_F(FakeVehicleHardwareTest, testSetHvacPropNotAvailable) {
-    int seatAreaIds[5] = {SEAT_1_LEFT, SEAT_1_RIGHT, SEAT_2_LEFT, SEAT_2_CENTER, SEAT_2_RIGHT};
-    for (int areaId : seatAreaIds) {
+    FakeVehicleHardwareTestHelper helper(getHardware());
+    auto hvacPowerOnConfig = std::move(getVehiclePropConfig(toInt(VehicleProperty::HVAC_POWER_ON)));
+    EXPECT_NE(hvacPowerOnConfig, nullptr);
+    for (auto& hvacPowerOnAreaConfig : hvacPowerOnConfig->areaConfigs) {
+        int hvacPowerAreaId = hvacPowerOnAreaConfig.areaId;
+        // Turn off HVAC_POWER_ON for only 1 area ID
         StatusCode status = setValue(VehiclePropValue{.prop = toInt(VehicleProperty::HVAC_POWER_ON),
-                                                      .areaId = areaId,
+                                                      .areaId = hvacPowerAreaId,
                                                       .value.int32Values = {0}});
+        EXPECT_EQ(status, StatusCode::OK);
 
-        ASSERT_EQ(status, StatusCode::OK);
+        for (auto& powerPropId : helper.getHvacPowerDependentProps()) {
+            auto powerPropConfig = std::move(getVehiclePropConfig(powerPropId));
+            EXPECT_NE(powerPropConfig, nullptr);
+            if (powerPropConfig->access == VehiclePropertyAccess::READ) {
+                continue;
+            }
+            auto propType = getPropType(powerPropId);
+            // Try setting a value at each area ID supported by the power dependent property
+            for (auto& powerPropAreaConfig : powerPropConfig->areaConfigs) {
+                int powerDependentAreaId = powerPropAreaConfig.areaId;
+                auto val = VehiclePropValue{.prop = powerPropId, .areaId = powerDependentAreaId};
+                if (propType == VehiclePropertyType::FLOAT) {
+                    val.value.floatValues.emplace_back(20);
+                } else {
+                    val.value.int32Values.emplace_back(1);
+                }
+                status = setValue(val);
 
-        for (size_t i = 0; i < sizeof(HVAC_POWER_PROPERTIES) / sizeof(int32_t); i++) {
-            int powerPropId = HVAC_POWER_PROPERTIES[i];
-            for (int powerDependentAreaId : seatAreaIds) {
-                StatusCode status = setValue(VehiclePropValue{.prop = powerPropId,
-                                                              .areaId = powerDependentAreaId,
-                                                              .value.int32Values = {1}});
-
-                if (areaId == powerDependentAreaId) {
+                // If the current area ID is contained within the HVAC_POWER_ON area ID
+                // turned off, then setValue should fail and a StatusCode error should be
+                // returned. Otherwise, an ok StatusCode should be returned.
+                if ((hvacPowerAreaId & powerDependentAreaId) == powerDependentAreaId) {
                     EXPECT_EQ(status, StatusCode::NOT_AVAILABLE_DISABLED);
                 } else {
                     EXPECT_EQ(status, StatusCode::OK);
@@ -1749,38 +1804,48 @@
         // on this value from any power dependent property values other than those with the same
         // areaId.
         setValue(VehiclePropValue{.prop = toInt(VehicleProperty::HVAC_POWER_ON),
-                                  .areaId = areaId,
+                                  .areaId = hvacPowerAreaId,
                                   .value.int32Values = {1}});
     }
 }
 
 TEST_F(FakeVehicleHardwareTest, testHvacPowerOnSendCurrentHvacPropValues) {
-    int seatAreaIds[5] = {SEAT_1_LEFT, SEAT_1_RIGHT, SEAT_2_LEFT, SEAT_2_CENTER, SEAT_2_RIGHT};
-    for (int areaId : seatAreaIds) {
+    FakeVehicleHardwareTestHelper helper(getHardware());
+    auto hvacPowerOnConfig = std::move(getVehiclePropConfig(toInt(VehicleProperty::HVAC_POWER_ON)));
+    EXPECT_NE(hvacPowerOnConfig, nullptr);
+    for (auto& hvacPowerOnAreaConfig : hvacPowerOnConfig->areaConfigs) {
+        int hvacPowerAreaId = hvacPowerOnAreaConfig.areaId;
         StatusCode status = setValue(VehiclePropValue{.prop = toInt(VehicleProperty::HVAC_POWER_ON),
-                                                      .areaId = areaId,
+                                                      .areaId = hvacPowerAreaId,
                                                       .value.int32Values = {0}});
-
-        ASSERT_EQ(status, StatusCode::OK);
-
-        clearChangedProperties();
-        setValue(VehiclePropValue{.prop = toInt(VehicleProperty::HVAC_POWER_ON),
-                                  .areaId = areaId,
-                                  .value.int32Values = {1}});
-
+        EXPECT_EQ(status, StatusCode::OK);
         auto events = getChangedProperties();
-        // If we turn HVAC power on, we expect to receive one property event for every HVAC prop
-        // areas plus one event for HVAC_POWER_ON.
-        std::vector<int32_t> changedPropIds;
-        for (size_t i = 0; i < sizeof(HVAC_POWER_PROPERTIES) / sizeof(int32_t); i++) {
-            changedPropIds.push_back(HVAC_POWER_PROPERTIES[i]);
-        }
-        changedPropIds.push_back(toInt(VehicleProperty::HVAC_POWER_ON));
-
         for (const auto& event : events) {
-            EXPECT_EQ(event.areaId, areaId);
-            EXPECT_THAT(event.prop, AnyOfArray(changedPropIds));
+            // Ignore HVAC_POWER_ON event
+            if (event.prop == toInt(VehicleProperty::HVAC_POWER_ON)) {
+                continue;
+            }
+            EXPECT_THAT(event.prop, AnyOfArray(helper.getHvacPowerDependentProps()));
+            EXPECT_EQ((hvacPowerAreaId & event.areaId), hvacPowerAreaId);
+            EXPECT_EQ(event.status, VehiclePropertyStatus::UNAVAILABLE);
         }
+        clearChangedProperties();
+
+        status = setValue(VehiclePropValue{.prop = toInt(VehicleProperty::HVAC_POWER_ON),
+                                           .areaId = hvacPowerAreaId,
+                                           .value.int32Values = {1}});
+        EXPECT_EQ(status, StatusCode::OK);
+        events = getChangedProperties();
+        for (const auto& event : events) {
+            // Ignore HVAC_POWER_ON event
+            if (event.prop == toInt(VehicleProperty::HVAC_POWER_ON)) {
+                continue;
+            }
+            EXPECT_THAT(event.prop, AnyOfArray(helper.getHvacPowerDependentProps()));
+            EXPECT_EQ((hvacPowerAreaId & event.areaId), hvacPowerAreaId);
+            EXPECT_EQ(event.status, VehiclePropertyStatus::AVAILABLE);
+        }
+        clearChangedProperties();
     }
 }
 
@@ -3016,13 +3081,8 @@
 
     // Config array values from HVAC_TEMPERATURE_SET in DefaultProperties.json
     auto configs = getHardware()->getAllPropertyConfigs();
-    VehiclePropConfig* hvacTemperatureSetConfig = nullptr;
-    for (auto& config : configs) {
-        if (config.prop == toInt(VehicleProperty::HVAC_TEMPERATURE_SET)) {
-            hvacTemperatureSetConfig = &config;
-            break;
-        }
-    }
+    auto hvacTemperatureSetConfig =
+            std::move(getVehiclePropConfig(toInt(VehicleProperty::HVAC_TEMPERATURE_SET)));
     EXPECT_NE(hvacTemperatureSetConfig, nullptr);
 
     auto& hvacTemperatureSetConfigArray = hvacTemperatureSetConfig->configArray;
diff --git a/automotive/vehicle/aidl/impl/grpc/GRPCVehicleHardware.h b/automotive/vehicle/aidl/impl/grpc/GRPCVehicleHardware.h
index e740da7..ddd620e 100644
--- a/automotive/vehicle/aidl/impl/grpc/GRPCVehicleHardware.h
+++ b/automotive/vehicle/aidl/impl/grpc/GRPCVehicleHardware.h
@@ -82,6 +82,10 @@
 
     bool waitForConnected(std::chrono::milliseconds waitTime);
 
+  protected:
+    std::shared_mutex mCallbackMutex;
+    std::unique_ptr<const PropertyChangeCallback> mOnPropChange;
+
   private:
     void ValuePollingLoop();
 
@@ -90,8 +94,6 @@
     std::unique_ptr<proto::VehicleServer::Stub> mGrpcStub;
     std::thread mValuePollingThread;
 
-    std::shared_mutex mCallbackMutex;
-    std::unique_ptr<const PropertyChangeCallback> mOnPropChange;
     std::unique_ptr<const PropertySetErrorCallback> mOnSetErr;
 
     std::mutex mShutdownMutex;
diff --git a/automotive/vehicle/aidl/impl/grpc/utils/proto_message_converter/src/ProtoMessageConverter.cpp b/automotive/vehicle/aidl/impl/grpc/utils/proto_message_converter/src/ProtoMessageConverter.cpp
index 6cbc7e5..6b789bb 100644
--- a/automotive/vehicle/aidl/impl/grpc/utils/proto_message_converter/src/ProtoMessageConverter.cpp
+++ b/automotive/vehicle/aidl/impl/grpc/utils/proto_message_converter/src/ProtoMessageConverter.cpp
@@ -73,6 +73,11 @@
         protoACfg->set_max_float_value(areaConfig.maxFloatValue);
         protoACfg->set_min_int32_value(areaConfig.minInt32Value);
         protoACfg->set_max_int32_value(areaConfig.maxInt32Value);
+        if (areaConfig.supportedEnumValues.has_value()) {
+            for (auto& supportedEnumValue : areaConfig.supportedEnumValues.value()) {
+                protoACfg->add_supported_enum_values(supportedEnumValue);
+            }
+        }
     }
 }
 
@@ -87,7 +92,7 @@
     COPY_PROTOBUF_VEC_TO_VHAL_TYPE(in, config_array, out, configArray);
 
     auto cast_to_acfg = [](const proto::VehicleAreaConfig& protoAcfg) {
-        return aidl_vehicle::VehicleAreaConfig{
+        auto vehicleAreaConfig = aidl_vehicle::VehicleAreaConfig{
                 .areaId = protoAcfg.area_id(),
                 .minInt32Value = protoAcfg.min_int32_value(),
                 .maxInt32Value = protoAcfg.max_int32_value(),
@@ -96,6 +101,9 @@
                 .minFloatValue = protoAcfg.min_float_value(),
                 .maxFloatValue = protoAcfg.max_float_value(),
         };
+        COPY_PROTOBUF_VEC_TO_VHAL_TYPE(protoAcfg, supported_enum_values, (&vehicleAreaConfig),
+                                       supportedEnumValues.value());
+        return vehicleAreaConfig;
     };
     CAST_COPY_PROTOBUF_VEC_TO_VHAL_TYPE(in, area_configs, out, areaConfigs, cast_to_acfg);
 }
diff --git a/automotive/vehicle/aidl/impl/proto/android/hardware/automotive/vehicle/StatusCode.proto b/automotive/vehicle/aidl/impl/proto/android/hardware/automotive/vehicle/StatusCode.proto
index 63d7933..95e766a 100644
--- a/automotive/vehicle/aidl/impl/proto/android/hardware/automotive/vehicle/StatusCode.proto
+++ b/automotive/vehicle/aidl/impl/proto/android/hardware/automotive/vehicle/StatusCode.proto
@@ -38,6 +38,37 @@
 
     /* Something unexpected has happened in Vehicle HAL */
     INTERNAL_ERROR = 5;
+
+    /**
+     * For features that are not available because the underlying feature is
+     * disabled.
+     */
+    NOT_AVAILABLE_DISABLED = 6;
+
+    /**
+     * For features that are not available because the vehicle speed is too low.
+     */
+    NOT_AVAILABLE_SPEED_LOW = 7;
+
+    /**
+     * For features that are not available because the vehicle speed is too
+     * high.
+     */
+    NOT_AVAILABLE_SPEED_HIGH = 8;
+
+    /**
+     * For features that are not available because of bad camera or sensor
+     * visibility. Examples might be bird poop blocking the camera or a bumper
+     * cover blocking an ultrasonic sensor.
+     */
+    NOT_AVAILABLE_POOR_VISIBILITY = 9;
+
+    /**
+     * The feature cannot be accessed due to safety reasons. Eg. System could be
+     * in a faulty state, an object or person could be blocking the requested
+     * operation such as closing a trunk door, etc.
+     */
+    NOT_AVAILABLE_SAFETY = 10;
 };
 
 message VehicleHalCallStatus {
diff --git a/automotive/vehicle/aidl/impl/proto/android/hardware/automotive/vehicle/VehicleAreaConfig.proto b/automotive/vehicle/aidl/impl/proto/android/hardware/automotive/vehicle/VehicleAreaConfig.proto
index b5b7e80..ddc64d9 100644
--- a/automotive/vehicle/aidl/impl/proto/android/hardware/automotive/vehicle/VehicleAreaConfig.proto
+++ b/automotive/vehicle/aidl/impl/proto/android/hardware/automotive/vehicle/VehicleAreaConfig.proto
@@ -36,4 +36,11 @@
 
     float min_float_value = 6;
     float max_float_value = 7;
+
+    /**
+     * If the property has a @data_enum, then it is possible to specify a supported subset of the
+     * @data_enum. If the property has a @data_enum and supported_enum_values is null, then it is
+     * assumed all @data_enum values are supported unless specified through another mechanism.
+     */
+    repeated int64 supported_enum_values = 8;
 };
diff --git a/automotive/vehicle/aidl/impl/utils/common/include/PropertyUtils.h b/automotive/vehicle/aidl/impl/utils/common/include/PropertyUtils.h
index e41ec30..78b61f7 100644
--- a/automotive/vehicle/aidl/impl/utils/common/include/PropertyUtils.h
+++ b/automotive/vehicle/aidl/impl/utils/common/include/PropertyUtils.h
@@ -98,11 +98,6 @@
 constexpr int HVAC_RIGHT = SEAT_1_RIGHT | SEAT_2_RIGHT;
 constexpr int HVAC_ALL = HVAC_LEFT | HVAC_RIGHT;
 
-const int32_t HVAC_POWER_PROPERTIES[] = {
-        toInt(propertyutils_impl::VehicleProperty::HVAC_FAN_SPEED),
-        toInt(propertyutils_impl::VehicleProperty::HVAC_FAN_DIRECTION),
-};
-
 }  // namespace vehicle
 }  // namespace automotive
 }  // namespace hardware
diff --git a/automotive/vehicle/aidl/impl/utils/test_vendor_properties/Android.bp b/automotive/vehicle/aidl/impl/utils/test_vendor_properties/Android.bp
index 62c89ac..f7da7e0 100644
--- a/automotive/vehicle/aidl/impl/utils/test_vendor_properties/Android.bp
+++ b/automotive/vehicle/aidl/impl/utils/test_vendor_properties/Android.bp
@@ -26,5 +26,6 @@
     visibility: [
         "//hardware/interfaces/automotive/vehicle/aidl:__subpackages__",
         "//packages/services/Car:__subpackages__",
+        "//cts/tests/tests/car_permission_tests",
     ],
 }
diff --git a/automotive/vehicle/aidl/impl/vhal/Android.bp b/automotive/vehicle/aidl/impl/vhal/Android.bp
index 4feea79..c29345f 100644
--- a/automotive/vehicle/aidl/impl/vhal/Android.bp
+++ b/automotive/vehicle/aidl/impl/vhal/Android.bp
@@ -19,7 +19,7 @@
 }
 
 cc_binary {
-    name: "android.hardware.automotive.vehicle@V1-default-service",
+    name: "android.hardware.automotive.vehicle@V3-default-service",
     vendor: true,
     defaults: [
         "FakeVehicleHardwareDefaults",
@@ -68,7 +68,7 @@
 }
 
 cc_fuzz {
-    name: "android.hardware.automotive.vehicle@V1-default-service_fuzzer",
+    name: "android.hardware.automotive.vehicle-default-service_fuzzer",
     vendor: true,
     defaults: [
         "FakeVehicleHardwareDefaults",
diff --git a/automotive/vehicle/aidl/impl/vhal/vhal-default-service.rc b/automotive/vehicle/aidl/impl/vhal/vhal-default-service.rc
index 19267cd..9fa7b98 100644
--- a/automotive/vehicle/aidl/impl/vhal/vhal-default-service.rc
+++ b/automotive/vehicle/aidl/impl/vhal/vhal-default-service.rc
@@ -1,4 +1,4 @@
-service vendor.vehicle-hal-default /vendor/bin/hw/android.hardware.automotive.vehicle@V1-default-service
+service vendor.vehicle-hal-default /vendor/bin/hw/android.hardware.automotive.vehicle@V3-default-service
     class early_hal
     user vehicle_network
     group system inet
diff --git a/automotive/vehicle/aidl_property/aidl_api/android.hardware.automotive.vehicle.property/current/android/hardware/automotive/vehicle/VehicleProperty.aidl b/automotive/vehicle/aidl_property/aidl_api/android.hardware.automotive.vehicle.property/current/android/hardware/automotive/vehicle/VehicleProperty.aidl
index ba75e7b..231186f 100644
--- a/automotive/vehicle/aidl_property/aidl_api/android.hardware.automotive.vehicle.property/current/android/hardware/automotive/vehicle/VehicleProperty.aidl
+++ b/automotive/vehicle/aidl_property/aidl_api/android.hardware.automotive.vehicle.property/current/android/hardware/automotive/vehicle/VehicleProperty.aidl
@@ -245,6 +245,7 @@
   SUPPORTED_PROPERTY_IDS = (((0x0F48 + 0x10000000) + 0x01000000) + 0x00410000) /* 289476424 */,
   SHUTDOWN_REQUEST = (((0x0F49 + android.hardware.automotive.vehicle.VehiclePropertyGroup.SYSTEM) + android.hardware.automotive.vehicle.VehicleArea.GLOBAL) + android.hardware.automotive.vehicle.VehiclePropertyType.INT32) /* 289410889 */,
   VEHICLE_IN_USE = (((0x0F4A + android.hardware.automotive.vehicle.VehiclePropertyGroup.SYSTEM) + android.hardware.automotive.vehicle.VehicleArea.GLOBAL) + android.hardware.automotive.vehicle.VehiclePropertyType.BOOLEAN) /* 287313738 */,
+  CLUSTER_HEARTBEAT = (((0x0F4B + android.hardware.automotive.vehicle.VehiclePropertyGroup.SYSTEM) + android.hardware.automotive.vehicle.VehicleArea.GLOBAL) + android.hardware.automotive.vehicle.VehiclePropertyType.MIXED) /* 299896651 */,
   AUTOMATIC_EMERGENCY_BRAKING_ENABLED = (((0x1000 + android.hardware.automotive.vehicle.VehiclePropertyGroup.SYSTEM) + android.hardware.automotive.vehicle.VehicleArea.GLOBAL) + android.hardware.automotive.vehicle.VehiclePropertyType.BOOLEAN) /* 287313920 */,
   AUTOMATIC_EMERGENCY_BRAKING_STATE = (((0x1001 + android.hardware.automotive.vehicle.VehiclePropertyGroup.SYSTEM) + android.hardware.automotive.vehicle.VehicleArea.GLOBAL) + android.hardware.automotive.vehicle.VehiclePropertyType.INT32) /* 289411073 */,
   FORWARD_COLLISION_WARNING_ENABLED = (((0x1002 + android.hardware.automotive.vehicle.VehiclePropertyGroup.SYSTEM) + android.hardware.automotive.vehicle.VehicleArea.GLOBAL) + android.hardware.automotive.vehicle.VehiclePropertyType.BOOLEAN) /* 287313922 */,
diff --git a/automotive/vehicle/aidl_property/android/hardware/automotive/vehicle/VehicleProperty.aidl b/automotive/vehicle/aidl_property/android/hardware/automotive/vehicle/VehicleProperty.aidl
index 7d88810..af2e903 100644
--- a/automotive/vehicle/aidl_property/android/hardware/automotive/vehicle/VehicleProperty.aidl
+++ b/automotive/vehicle/aidl_property/android/hardware/automotive/vehicle/VehicleProperty.aidl
@@ -4487,6 +4487,20 @@
     VEHICLE_IN_USE =
             0x0F4A + VehiclePropertyGroup.SYSTEM + VehicleArea.GLOBAL + VehiclePropertyType.BOOLEAN,
 
+    /**
+     * Sends the heartbeat signal to ClusterOS.
+     *
+     * int64[0]: epochTimeNs
+     * int64[1]: the visibility of ClusterUI, 0 - invisible, 1 - visible
+     * bytes: the app specific metadata, this can be empty when ClusterHomeService use the heartbeat
+     *     to deliver the change of the visibility.
+     *
+     * @change_mode VehiclePropertyChangeMode.ON_CHANGE
+     * @access VehiclePropertyAccess.WRITE
+     */
+    CLUSTER_HEARTBEAT =
+            0x0F4B + VehiclePropertyGroup.SYSTEM + VehicleArea.GLOBAL + VehiclePropertyType.MIXED,
+
     /***********************************************************************************************
      * Start of ADAS Properties
      *
@@ -4737,11 +4751,11 @@
      *
      * Commands to activate and suspend LCA.
      *
-     * When the command ACTIVATE from LaneCenteringAssistCommmand is sent,
+     * When the command ACTIVATE from LaneCenteringAssistCommand is sent,
      * LANE_CENTERING_ASSIST_STATE must be set to LaneCenteringAssistState#ACTIVATION_REQUESTED.
      * When the ACTIVATE command succeeds, LANE_CENTERING_ASSIST_STATE must be set to
      * LaneCenteringAssistState#ACTIVATED. When the command DEACTIVATE from
-     * LaneCenteringAssistCommmand succeeds, LANE_CENTERING_ASSIST_STATE must be set to
+     * LaneCenteringAssistCommand succeeds, LANE_CENTERING_ASSIST_STATE must be set to
      * LaneCenteringAssistState#ENABLED.
      *
      * For the global area ID (0), the VehicleAreaConfig#supportedEnumValues must be defined unless
@@ -4757,7 +4771,7 @@
      *
      * @change_mode VehiclePropertyChangeMode.ON_CHANGE
      * @access VehiclePropertyAccess.WRITE
-     * @data_enum LaneCenteringAssistCommmand
+     * @data_enum LaneCenteringAssistCommand
      */
     LANE_CENTERING_ASSIST_COMMAND =
             0x100B + VehiclePropertyGroup.SYSTEM + VehicleArea.GLOBAL + VehiclePropertyType.INT32,
diff --git a/automotive/vehicle/proto/Android.bp b/automotive/vehicle/proto/Android.bp
index 683f128..e7dabcf 100644
--- a/automotive/vehicle/proto/Android.bp
+++ b/automotive/vehicle/proto/Android.bp
@@ -27,6 +27,7 @@
     visibility: [
         "//hardware/interfaces/automotive/vehicle:__subpackages__",
         "//device/generic/car/emulator:__subpackages__",
+        "//system/software_defined_vehicle/core_services:__subpackages__",
     ],
     vendor: true,
     host_supported: true,
diff --git a/automotive/vehicle/vts/src/VtsHalAutomotiveVehicle_TargetTest.cpp b/automotive/vehicle/vts/src/VtsHalAutomotiveVehicle_TargetTest.cpp
index 8bcad1e..3dca0ae 100644
--- a/automotive/vehicle/vts/src/VtsHalAutomotiveVehicle_TargetTest.cpp
+++ b/automotive/vehicle/vts/src/VtsHalAutomotiveVehicle_TargetTest.cpp
@@ -115,6 +115,9 @@
 };
 
 class VtsHalAutomotiveVehicleTargetTest : public testing::TestWithParam<ServiceDescriptor> {
+  protected:
+    bool checkIsSupported(int32_t propertyId);
+
   public:
     void verifyProperty(VehicleProperty propId, VehiclePropertyAccess access,
                         VehiclePropertyChangeMode changeMode, VehiclePropertyGroup group,
@@ -155,7 +158,7 @@
     }
 }
 
-// Test getAllPropConfig() returns at least 4 property configs.
+// Test getAllPropConfigs() returns at least 1 property configs.
 TEST_P(VtsHalAutomotiveVehicleTargetTest, getAllPropConfigs) {
     ALOGD("VtsHalAutomotiveVehicleTargetTest::getAllPropConfigs");
 
@@ -163,25 +166,29 @@
 
     ASSERT_TRUE(result.ok()) << "Failed to get all property configs, error: "
                              << result.error().message();
-    ASSERT_GE(result.value().size(), 4u) << StringPrintf(
-            "Expect to get at least 4 property configs, got %zu", result.value().size());
+    ASSERT_GE(result.value().size(), 1u) << StringPrintf(
+            "Expect to get at least 1 property config, got %zu", result.value().size());
 }
 
-// Test getPropConfigs() can query all properties listed in CDD.
-TEST_P(VtsHalAutomotiveVehicleTargetTest, getRequiredPropConfigs) {
+// Test getPropConfigs() can query properties returned by getAllPropConfigs.
+TEST_P(VtsHalAutomotiveVehicleTargetTest, getPropConfigsWithValidProps) {
     ALOGD("VtsHalAutomotiveVehicleTargetTest::getRequiredPropConfigs");
 
-    // Check the properties listed in CDD
-    std::vector<int32_t> properties = {
-            toInt(VehicleProperty::GEAR_SELECTION), toInt(VehicleProperty::NIGHT_MODE),
-            toInt(VehicleProperty::PARKING_BRAKE_ON), toInt(VehicleProperty::PERF_VEHICLE_SPEED)};
+    std::vector<int32_t> properties;
+    auto result = mVhalClient->getAllPropConfigs();
 
-    auto result = mVhalClient->getPropConfigs(properties);
+    ASSERT_TRUE(result.ok()) << "Failed to get all property configs, error: "
+                             << result.error().message();
+    for (const auto& cfgPtr : result.value()) {
+        properties.push_back(cfgPtr->getPropId());
+    }
+
+    result = mVhalClient->getPropConfigs(properties);
 
     ASSERT_TRUE(result.ok()) << "Failed to get required property config, error: "
                              << result.error().message();
-    ASSERT_EQ(result.value().size(), 4u)
-            << StringPrintf("Expect to get exactly 4 configs, got %zu", result.value().size());
+    ASSERT_EQ(result.value().size(), properties.size()) << StringPrintf(
+            "Expect to get exactly %zu configs, got %zu", properties.size(), result.value().size());
 }
 
 // Test getPropConfig() with an invalid propertyId returns an error code.
@@ -200,6 +207,9 @@
     ALOGD("VtsHalAutomotiveVehicleTargetTest::get");
 
     int32_t propId = toInt(VehicleProperty::PERF_VEHICLE_SPEED);
+    if (!checkIsSupported(propId)) {
+        GTEST_SKIP() << "Property: " << propId << " is not supported, skip the test";
+    }
     auto result = mVhalClient->getValueSync(*mVhalClient->createHalPropValue(propId));
 
     ASSERT_TRUE(result.ok()) << StringPrintf("Failed to get value for property: %" PRId32
@@ -285,6 +295,10 @@
     ALOGD("VtsHalAutomotiveVehicleTargetTest::setNotWritableProp");
 
     int32_t propId = toInt(VehicleProperty::PERF_VEHICLE_SPEED);
+    if (!checkIsSupported(propId)) {
+        GTEST_SKIP() << "Property: " << propId << " is not supported, skip the test";
+    }
+
     auto getValueResult = mVhalClient->getValueSync(*mVhalClient->createHalPropValue(propId));
     ASSERT_TRUE(getValueResult.ok())
             << StringPrintf("Failed to get value for property: %" PRId32 ", error: %s", propId,
@@ -325,6 +339,9 @@
     ALOGD("VtsHalAutomotiveVehicleTargetTest::subscribeAndUnsubscribe");
 
     int32_t propId = toInt(VehicleProperty::PERF_VEHICLE_SPEED);
+    if (!checkIsSupported(propId)) {
+        GTEST_SKIP() << "Property: " << propId << " is not supported, skip the test";
+    }
 
     auto propConfigsResult = mVhalClient->getPropConfigs({propId});
 
@@ -414,6 +431,9 @@
     }
 
     int32_t propId = toInt(VehicleProperty::PARKING_BRAKE_ON);
+    if (!checkIsSupported(propId)) {
+        GTEST_SKIP() << "Property: " << propId << " is not supported, skip the test";
+    }
     auto prop = mVhalClient->createHalPropValue(propId);
 
     auto result = mVhalClient->getValueSync(*prop);
@@ -865,6 +885,17 @@
                    VehicleArea::GLOBAL, VehiclePropertyType::INT32);
 }
 
+TEST_P(VtsHalAutomotiveVehicleTargetTest, verifyClusterHeartbeatConfig) {
+    verifyProperty(VehicleProperty::CLUSTER_HEARTBEAT, VehiclePropertyAccess::WRITE,
+                   VehiclePropertyChangeMode::ON_CHANGE, VehiclePropertyGroup::SYSTEM,
+                   VehicleArea::GLOBAL, VehiclePropertyType::MIXED);
+}
+
+bool VtsHalAutomotiveVehicleTargetTest::checkIsSupported(int32_t propertyId) {
+    auto result = mVhalClient->getPropConfigs({propertyId});
+    return result.ok();
+}
+
 std::vector<ServiceDescriptor> getDescriptors() {
     std::vector<ServiceDescriptor> descriptors;
     for (std::string name : getAidlHalInstanceNames(IVehicle::descriptor)) {
diff --git a/biometrics/common/util/include/util/Util.h b/biometrics/common/util/include/util/Util.h
index da19dc6..efd66bc 100644
--- a/biometrics/common/util/include/util/Util.h
+++ b/biometrics/common/util/include/util/Util.h
@@ -23,6 +23,9 @@
 #include <thread>
 #include <vector>
 
+#include <android-base/parseint.h>
+using ::android::base::ParseInt;
+
 namespace aidl::android::hardware::biometrics {
 
 #define SLEEP_MS(x) \
@@ -64,6 +67,87 @@
                 std::sregex_token_iterator());
         return parts;
     }
+
+    // Returns a vector of integers for the string separated by comma,
+    // Empty vector is returned if there is any parsing error
+    static std::vector<int32_t> parseIntSequence(const std::string& str,
+                                                 const std::string& sep = ",") {
+        std::vector<std::string> seqs = Util::split(str, sep);
+        std::vector<int32_t> res;
+
+        for (const auto& seq : seqs) {
+            int32_t val;
+            if (ParseInt(seq, &val)) {
+                res.push_back(val);
+            } else {
+                LOG(WARNING) << "Invalid int sequence:" + str + " seq:" + seq;
+                res.clear();
+                break;
+            }
+        }
+
+        return res;
+    }
+
+    // Parses a single enrollment stage string in the format of
+    //     enroll_stage_spec: <duration>[-acquiredInfos]
+    //                                      duration: integerInMs
+    //                                      acquiredInfos: [info1,info2,...]
+    //
+    // Returns false if there is parsing error
+    //
+    static bool parseEnrollmentCaptureSingle(const std::string& str,
+                                             std::vector<std::vector<int32_t>>& res) {
+        std::vector<int32_t> defaultAcquiredInfo = {1};
+        bool aborted = true;
+
+        do {
+            std::smatch sms;
+            // Parses strings like "1000-[5,1]" or "500"
+            std::regex ex("((\\d+)(-\\[([\\d|,]+)\\])?)");
+            if (!regex_match(str.cbegin(), str.cend(), sms, ex)) break;
+            int32_t duration;
+            if (!ParseInt(sms.str(2), &duration)) break;
+            res.push_back({duration});
+            if (!sms.str(4).empty()) {
+                auto acqv = parseIntSequence(sms.str(4));
+                if (acqv.empty()) break;
+                res.push_back(acqv);
+            } else
+                res.push_back(defaultAcquiredInfo);
+            aborted = false;
+        } while (0);
+
+        return !aborted;
+    }
+
+    // Parses enrollment string consisting of one or more stages in the formst of
+    //  <enroll_stage_spec>[,enroll_stage_spec,...]
+    // Empty vector is returned in case of parsing error
+    static std::vector<std::vector<int32_t>> parseEnrollmentCapture(const std::string& str) {
+        std::vector<std::vector<int32_t>> res;
+
+        std::string s(str);
+        s.erase(std::remove_if(s.begin(), s.end(), ::isspace), s.end());
+        bool aborted = false;
+        std::smatch sms;
+        // Parses strings like "1000-[5,1],500,800-[6,5,1]"
+        //                               -------------- ----- ---------------
+        //  into parts:                       A       B       C
+        while (regex_search(s, sms, std::regex("^(,)?(\\d+(-\\[[\\d|,]+\\])?)"))) {
+            if (!parseEnrollmentCaptureSingle(sms.str(2), res)) {
+                aborted = true;
+                break;
+            }
+            s = sms.suffix();
+        }
+        if (aborted || s.length() != 0) {
+            res.clear();
+            LOG(ERROR) << "Failed to parse enrollment captures:" + str;
+        }
+
+        return res;
+    }
 };
 
 }  // namespace aidl::android::hardware::biometrics
diff --git a/biometrics/face/aidl/default/Android.bp b/biometrics/face/aidl/default/Android.bp
index 82ad917..7bc2198 100644
--- a/biometrics/face/aidl/default/Android.bp
+++ b/biometrics/face/aidl/default/Android.bp
@@ -8,20 +8,20 @@
 }
 
 filegroup {
-    name: "face-default.rc",
-    srcs: ["face-default.rc"],
+    name: "face-example.rc",
+    srcs: ["face-example.rc"],
 }
 
 filegroup {
-    name: "face-default.xml",
-    srcs: ["face-default.xml"],
+    name: "face-example.xml",
+    srcs: ["face-example.xml"],
 }
 
 cc_binary {
     name: "android.hardware.biometrics.face-service.example",
     relative_install_path: "hw",
-    init_rc: [":face-default.rc"],
-    vintf_fragments: [":face-default.xml"],
+    init_rc: [":face-example.rc"],
+    vintf_fragments: [":face-example.xml"],
     vendor: true,
     shared_libs: [
         "libbase",
diff --git a/biometrics/face/aidl/default/FakeFaceEngine.cpp b/biometrics/face/aidl/default/FakeFaceEngine.cpp
index 0f088f4..578231d 100644
--- a/biometrics/face/aidl/default/FakeFaceEngine.cpp
+++ b/biometrics/face/aidl/default/FakeFaceEngine.cpp
@@ -136,56 +136,127 @@
                                       const std::future<void>& cancel) {
     BEGIN_OP(FaceHalProperties::operation_authenticate_latency().value_or(0));
 
-    // Signal to the framework that we have begun authenticating.
-    AuthenticationFrame frame;
-    frame.data.acquiredInfo = AcquiredInfo::START;
-    frame.data.vendorCode = 0;
-    cb->onAuthenticationFrame(frame);
-
-    // Also signal that we have opened the camera.
-    frame = {};
-    frame.data.acquiredInfo = AcquiredInfo::FIRST_FRAME_RECEIVED;
-    frame.data.vendorCode = 0;
-    cb->onAuthenticationFrame(frame);
-
-    auto now = Util::getSystemNanoTime();
-    int64_t duration = FaceHalProperties::operation_authenticate_duration().value_or(0);
-    if (duration > 0) {
-        do {
-            SLEEP_MS(5);
-        } while (!Util::hasElapsed(now, duration));
-    }
-
-    if (FaceHalProperties::operation_authenticate_fails().value_or(false)) {
-        LOG(ERROR) << "Fail: operation_authenticate_fails";
-        cb->onError(Error::VENDOR, 0 /* vendorError */);
-        return;
-    }
-
-    if (FaceHalProperties::lockout().value_or(false)) {
-        LOG(ERROR) << "Fail: lockout";
-        cb->onLockoutPermanent();
-        cb->onError(Error::HW_UNAVAILABLE, 0 /* vendorError */);
-        return;
-    }
-
-    if (shouldCancel(cancel)) {
-        LOG(ERROR) << "Fail: cancel";
-        cb->onError(Error::CANCELED, 0 /* vendorCode */);
-        return;
-    }
-
     auto id = FaceHalProperties::enrollment_hit().value_or(0);
     auto enrolls = FaceHalProperties::enrollments();
     auto isEnrolled = std::find(enrolls.begin(), enrolls.end(), id) != enrolls.end();
-    if (id < 0 || !isEnrolled) {
-        LOG(ERROR) << (isEnrolled ? "invalid enrollment hit" : "Fail: not enrolled");
-        cb->onAuthenticationFailed();
+
+    auto vec2str = [](std::vector<AcquiredInfo> va) {
+        std::stringstream ss;
+        bool isFirst = true;
+        for (auto ac : va) {
+            if (!isFirst) ss << ",";
+            ss << std::to_string((int8_t)ac);
+            isFirst = false;
+        }
+        return ss.str();
+    };
+
+    // default behavior mimic face sensor in U
+    int64_t defaultAuthDuration = 500;
+    std::string defaultAcquiredInfo =
+            vec2str({AcquiredInfo::START, AcquiredInfo::FIRST_FRAME_RECEIVED});
+    if (!isEnrolled) {
+        std::vector<AcquiredInfo> v;
+        for (int i = 0; i < 56; i++) v.push_back(AcquiredInfo::NOT_DETECTED);
+        defaultAcquiredInfo += "," + vec2str(v);
+        defaultAuthDuration = 2100;
+    } else {
+        defaultAcquiredInfo += "," + vec2str({AcquiredInfo::TOO_BRIGHT, AcquiredInfo::TOO_BRIGHT,
+                                              AcquiredInfo::TOO_BRIGHT, AcquiredInfo::TOO_BRIGHT,
+                                              AcquiredInfo::GOOD, AcquiredInfo::GOOD});
+    }
+
+    int64_t now = Util::getSystemNanoTime();
+    int64_t duration =
+            FaceHalProperties::operation_authenticate_duration().value_or(defaultAuthDuration);
+    auto acquired =
+            FaceHalProperties::operation_authenticate_acquired().value_or(defaultAcquiredInfo);
+    auto acquiredInfos = Util::parseIntSequence(acquired);
+    int N = acquiredInfos.size();
+
+    if (N == 0) {
+        LOG(ERROR) << "Fail to parse authentiate acquired info: " + acquired;
         cb->onError(Error::UNABLE_TO_PROCESS, 0 /* vendorError */);
         return;
     }
 
-    cb->onAuthenticationSucceeded(id, {} /* hat */);
+    int i = 0;
+    do {
+        if (FaceHalProperties::lockout().value_or(false)) {
+            LOG(ERROR) << "Fail: lockout";
+            cb->onLockoutPermanent();
+            cb->onError(Error::HW_UNAVAILABLE, 0 /* vendorError */);
+            return;
+        }
+
+        if (FaceHalProperties::operation_authenticate_fails().value_or(false)) {
+            LOG(ERROR) << "Fail: operation_authenticate_fails";
+            cb->onAuthenticationFailed();
+            return;
+        }
+
+        auto err = FaceHalProperties::operation_authenticate_error().value_or(0);
+        if (err != 0) {
+            LOG(ERROR) << "Fail: operation_authenticate_error";
+            auto ec = convertError(err);
+            cb->onError(ec.first, ec.second);
+            return; /* simply terminating current operation for any user inserted error,
+                            revisit if tests need*/
+        }
+
+        if (shouldCancel(cancel)) {
+            LOG(ERROR) << "Fail: cancel";
+            cb->onError(Error::CANCELED, 0 /* vendorCode */);
+            return;
+        }
+
+        if (i < N) {
+            auto ac = convertAcquiredInfo(acquiredInfos[i]);
+            AuthenticationFrame frame;
+            frame.data.acquiredInfo = ac.first;
+            frame.data.vendorCode = ac.second;
+            cb->onAuthenticationFrame(frame);
+            LOG(INFO) << "AcquiredInfo:" << i << ": (" << (int)ac.first << "," << (int)ac.second
+                      << ")";
+            i++;
+        }
+
+        SLEEP_MS(duration / N);
+    } while (!Util::hasElapsed(now, duration));
+
+    if (id > 0 && isEnrolled) {
+        cb->onAuthenticationSucceeded(id, {} /* hat */);
+        return;
+    } else {
+        LOG(ERROR) << "Fail: face not enrolled";
+        cb->onAuthenticationFailed();
+        cb->onError(Error::TIMEOUT, 0 /* vendorError*/);
+        return;
+    }
+}
+
+std::pair<AcquiredInfo, int32_t> FakeFaceEngine::convertAcquiredInfo(int32_t code) {
+    std::pair<AcquiredInfo, int32_t> res;
+    if (code > FACE_ACQUIRED_VENDOR_BASE) {
+        res.first = AcquiredInfo::VENDOR;
+        res.second = code - FACE_ACQUIRED_VENDOR_BASE;
+    } else {
+        res.first = (AcquiredInfo)code;
+        res.second = 0;
+    }
+    return res;
+}
+
+std::pair<Error, int32_t> FakeFaceEngine::convertError(int32_t code) {
+    std::pair<Error, int32_t> res;
+    if (code > FACE_ERROR_VENDOR_BASE) {
+        res.first = Error::VENDOR;
+        res.second = code - FACE_ERROR_VENDOR_BASE;
+    } else {
+        res.first = (Error)code;
+        res.second = 0;
+    }
+    return res;
 }
 
 void FakeFaceEngine::detectInteractionImpl(ISessionCallback* cb, const std::future<void>& cancel) {
@@ -315,4 +386,4 @@
     cb->onLockoutCleared();
 }
 
-}  // namespace aidl::android::hardware::biometrics::face
\ No newline at end of file
+}  // namespace aidl::android::hardware::biometrics::face
diff --git a/biometrics/face/aidl/default/FakeFaceEngine.h b/biometrics/face/aidl/default/FakeFaceEngine.h
index edb54ce..06dd396 100644
--- a/biometrics/face/aidl/default/FakeFaceEngine.h
+++ b/biometrics/face/aidl/default/FakeFaceEngine.h
@@ -16,6 +16,8 @@
 
 #pragma once
 
+#define LOG_TAG "FaceVirtualHal"
+
 #include <aidl/android/hardware/biometrics/common/SensorStrength.h>
 #include <aidl/android/hardware/biometrics/face/BnSession.h>
 #include <aidl/android/hardware/biometrics/face/FaceSensorType.h>
@@ -60,6 +62,12 @@
     void resetLockoutImpl(ISessionCallback* cb, const keymaster::HardwareAuthToken& /*hat*/);
 
     std::mt19937 mRandom;
+
+  private:
+    static constexpr int32_t FACE_ACQUIRED_VENDOR_BASE = 1000;
+    static constexpr int32_t FACE_ERROR_VENDOR_BASE = 1000;
+    std::pair<AcquiredInfo, int32_t> convertAcquiredInfo(int32_t code);
+    std::pair<Error, int32_t> convertError(int32_t code);
 };
 
-}  // namespace aidl::android::hardware::biometrics::face
\ No newline at end of file
+}  // namespace aidl::android::hardware::biometrics::face
diff --git a/biometrics/face/aidl/default/README.md b/biometrics/face/aidl/default/README.md
index 1655973..516a7aa 100644
--- a/biometrics/face/aidl/default/README.md
+++ b/biometrics/face/aidl/default/README.md
@@ -1,77 +1,63 @@
-# Virtual Face HAL
+# Face Virtual HAL (VHAL)
 
 This is a virtual HAL implementation that is backed by system properties
 instead of actual hardware. It's intended for testing and UI development
 on debuggable builds to allow devices to masquerade as alternative device
 types and for emulators.
+Note: The virtual face HAL feature development will be done in phases. Refer to this doc often for
+the latest supported features
 
-## Device Selection
+## Supported Devices
 
-You can either run the FakeFaceEngine on a [real device](#actual-device) or a [virtual device/cuttlefish](#getting-started-on-a-virtual-device-cuttlefish). This document should
-help you to get started on either one.
+The face virtual hal is automatically built in in all debug builds (userdebug and eng) for the latest pixel devices and CF.
+The instructions in this doc applies  to all
 
-After setting up a device, go ahead and try out [enrolling](#enrolling) & [authenticating](#authenticating)
+## Enabling Face Virtual HAL
 
-### Getting started on a Virtual Device (cuttlefish)
+On pixel devicse (non-CF), by default (after manufacture reset), Face VHAL is not enabled. Therefore real Face HAL is used.
+Face VHAL enabling is gated by the following two AND conditions:
+1. The Face VHAL feature flag (as part of Trunk-development strategy) must be tured until the flags life-cycle ends.
+2. The Face VHAL must be enabled via sysprop
+See adb commands below
 
+##Getting Stared
 
-Note, I'm running this via a cloudtop virtual device.
+A basic use case for a successful authentication via Face VHAL is given as an exmple below.
 
-1. Setup cuttlefish on cloudtop, See [this](https://g3doc.corp.google.com/company/teams/android/teampages/acloud/getting_started.md?cl=head) for more details.
-2. acloud create --local-image
-3. Enter in the shell command to disable hidl
-
+### Enabling VHAL
 ```shell
 $ adb root
-$ adb shell settings put secure com.android.server.biometrics.AuthService.hidlDisabled 1
-$ adb reboot
-```
-4. You should now be able to do fake enrollments and authentications (as seen down below)
-
-### Actual Device
-
-1. Modify your real devices make file (I.E. vendor/google/products/{YOUR_DEVICE}.mk)
-2. Ensure that there is no other face HAL that is being included by the device
-3. Add the following
-```
-PRODUCT_COPY_FILES += \
-    frameworks/native/data/etc/android.hardware.biometrics.face.xml:$(TARGET_COPY_OUT_PRODUCT)/etc/permissions/android.hardware.biometrics.face.xml
-
-PRODUCT_PACKAGES += \
-    android.hardware.biometrics.face-service.example \
-
-```
-4. Now build and flash m -j120 && flash
-5. Run the following commands
-
-```shell
-# This is a temporary workaround
-$ adb root
-$ adb shell setprop persist.vendor.face.virtual.type RGB
+$ adb shell device_config put biometrics_framework com.android.server.biometrics.face_vhal_feature true
+$ adb shell settings put secure biometric_virtual_enabled 1
 $ adb shell setprop persist.vendor.face.virtual.strength strong
-$ adb shell locksettings set-pin 0000
+$ adb shell setprop persist.vendor.face.virtual.type RGB
 $ adb reboot
 ```
 
-## Enrolling
+### Direct Enrollment
+```shell
+$ adb shell locksettings set-pin 0000
+$ adb shell setprop persist.vendor.face.virtual.enrollments 1
+$ adb shell cmd face syncadb shell cmd face sync
+```
+
+## Authenticating
+To authenticate successfully, the captured (hit) must match the enrollment id set above. To  trigger
+authentication failure, set the hit id to a different value.
+```shell
+$ adb shell setprop vendor.face.virtual.operation_authenticate_duration 800
+$ adb shell setprop vendor.face.virtual.enrollment_hit 1
+```
+Refer to face.sysprop for full supported features of authentication, such as error and acquiredInfo insertion
+
+
+## Enrollment via Setup
 
 ```shell
 # authenticar_id,bucket_id:duration:(true|false)....
 $ adb shell setprop vendor.face.virtual.next_enrollment 1,0:500:true,5:250:true,10:150:true,15:500:true
-$ adb shell am start -n com.android.settings/.biometrics.face.FaceEnrollIntroduction
+$ walk thru the manual enrollment process by following screen instructions
+
 # If you would like to get rid of the enrollment, run the follwoing command
 $ adb shell setprop persist.vendor.face.virtual.enrollments \"\"
 ```
-
-## Authenticating
-
-```shell
-# If enrollment hasn't been setup
-$ adb shell setprop persist.vendor.face.virtual.enrollments 1
-$ adb shell cmd face sync
-# After enrollment has been setup
-$ adb shell setprop vendor.face.virtual.operation_authenticate_duration 800
-$ adb shell setprop vendor.face.virtual.enrollment_hit 1
-# Power button press to simulate auth
-$ adb shell input keyevent 26
-```
diff --git a/biometrics/face/aidl/default/Session.cpp b/biometrics/face/aidl/default/Session.cpp
index 1188459..6235b83 100644
--- a/biometrics/face/aidl/default/Session.cpp
+++ b/biometrics/face/aidl/default/Session.cpp
@@ -18,6 +18,9 @@
 
 #include "Session.h"
 
+#undef LOG_TAG
+#define LOG_TAG "FaceVirtualHalSession"
+
 namespace aidl::android::hardware::biometrics::face {
 
 constexpr size_t MAX_WORKER_QUEUE_SIZE = 5;
diff --git a/biometrics/face/aidl/default/apex/Android.bp b/biometrics/face/aidl/default/apex/Android.bp
index 2f39a08..86c4e12 100644
--- a/biometrics/face/aidl/default/apex/Android.bp
+++ b/biometrics/face/aidl/default/apex/Android.bp
@@ -16,27 +16,14 @@
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
-apex_key {
-    name: "com.android.hardware.biometrics.face.key",
-    public_key: "com.android.hardware.biometrics.face.avbpubkey",
-    private_key: "com.android.hardware.biometrics.face.pem",
-}
-
-android_app_certificate {
-    name: "com.android.hardware.biometrics.face.certificate",
-    certificate: "com.android.hardware.biometrics.face",
-}
-
 apex {
-    name: "com.android.hardware.biometrics.face",
+    name: "com.android.hardware.biometrics.face.virtual",
     manifest: "manifest.json",
     file_contexts: "file_contexts",
-    key: "com.android.hardware.biometrics.face.key",
-    certificate: ":com.android.hardware.biometrics.face.certificate",
+    key: "com.android.hardware.key",
+    certificate: ":com.android.hardware.certificate",
     updatable: false,
-
     vendor: true,
-    use_vndk_as_stable: true,
 
     binaries: [
         // hal
@@ -44,11 +31,9 @@
     ],
     prebuilts: [
         // init_rc
-        "face-default-apex.rc",
+        "face-example-apex.rc",
         // vintf_fragment
-        "face-default-apex.xml",
-        // permission
-        "android.hardware.biometrics.face.prebuilt.xml",
+        "face-example-apex.xml",
     ],
 
     overrides: [
@@ -57,23 +42,21 @@
 }
 
 prebuilt_etc {
-    name: "face-default-apex.rc",
-    src: ":gen-face-default-apex.rc",
-    vendor: true,
+    name: "face-example-apex.rc",
+    src: ":gen-face-example-apex.rc",
     installable: false,
 }
 
 genrule {
-    name: "gen-face-default-apex.rc",
-    srcs: [":face-default.rc"],
-    out: ["face-default-apex.rc"],
-    cmd: "sed -e 's@/vendor/bin/@/apex/com.android.hardware.biometrics.face/bin/@' $(in) > $(out)",
+    name: "gen-face-example-apex.rc",
+    srcs: [":face-example.rc"],
+    out: ["face-example-apex.rc"],
+    cmd: "sed -e 's@/vendor/bin/@/apex/com.android.hardware.biometrics.face.virtual/bin/@' $(in) > $(out)",
 }
 
 prebuilt_etc {
-    name: "face-default-apex.xml",
-    src: ":face-default.xml",
+    name: "face-example-apex.xml",
+    src: ":face-example.xml",
     sub_dir: "vintf",
-    vendor: true,
     installable: false,
 }
diff --git a/biometrics/face/aidl/default/apex/com.android.hardware.biometrics.face.avbpubkey b/biometrics/face/aidl/default/apex/com.android.hardware.biometrics.face.avbpubkey
deleted file mode 100644
index 9f358ff..0000000
--- a/biometrics/face/aidl/default/apex/com.android.hardware.biometrics.face.avbpubkey
+++ /dev/null
Binary files differ
diff --git a/biometrics/face/aidl/default/apex/com.android.hardware.biometrics.face.pem b/biometrics/face/aidl/default/apex/com.android.hardware.biometrics.face.pem
deleted file mode 100644
index ad8f57d..0000000
--- a/biometrics/face/aidl/default/apex/com.android.hardware.biometrics.face.pem
+++ /dev/null
@@ -1,52 +0,0 @@
------BEGIN PRIVATE KEY-----
-MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQCoZ28KVXxB9kkX
-zPhi8pVSmiMU0xchU4PkoOvFzmr9t5b7rA1zmzOLjkNWMrxt1XCUEfOgT3N50z5T
-484dpEZBrwIH31NqSOr/T8mG5frZAkNg0WqfgV+AG81mCuA+nG4a08fmDL4nEzVg
-irQvWpXzRCNIn+LEx+gG4I2KG8EGWDiFnzXwSFJG4n60rfLQNHgsejv/06BmPCnS
-gp06LhqJTO2oJKCJVQxfO0TPNUd9FSVSXdWuHcHE2gwoHM/7C/10Bdx8XXCMbAQR
-a4d3moH5oRuhh1841PtIQ0ozw/vHapCTmdMbjmgbwpXZ49DfvJl2cnz5c5G/CUO1
-9CkLDdxffsHh48jLUzH1nRgcWW2CAnSIs8nGjScyOKB+gn831ke8agJGbVHs1Cp/
-ONbMZeQIhEL0kderI1vVoufeBf38/I93rpz6PXp5NiTwOnVdEik595/W7oldr/rM
-taKvWwfnjml+Z1uzJWWDKPnS+onxBVcoBGFhiewIejPz3UjncMiHW5QAx/BzfGgh
-UmFO0vsh8qrEfAqT4AqL4uCuyVm0JmugdWKoeQISh5i4+HMmvPaudd+8yF0plr10
-+pyNGkLZm4NBJxOD7V0AMjfTIpKRbmV8xnCAnWQ+xx/qWxHAZ0wfbZXXF0m6L6po
-dVwJJI7EnuQbAkbXnzMtCTQToZTSVwIDAQABAoICAAGjGJNY15kYKO3xzXWMyfXT
-gl7L9Im1TNVwP3Dpu+S7U0NSd1w12Iju35znzlwhx7/j8skOrKubaZvM9ztJ79Yb
-1CDs3PWhP6OVJeGvvHU9zkp59RexQ5Ma8hXskIroE2WJ97bQgRkfi/r9x8wKc39T
-aYv/SrTC0SPr+YRFSjMvfV35kvLC759slgwkmsH6ZWatSeyhPooJfX1kTRBi08A2
-i4lOBD+Bhtn2jG/+1eYtFyYXVaHx/E9XfU6QhSPgIhBULdujPucmj6pc4yRYnKxA
-32QxGc35u0QHEqJ9/iWAoporIMAmU/Qp7phl9g+OvxrFkloMc3cp3GSMh8k2bJUY
-nRvk0IPG1bF7jwezHbQGTwTlguJlWPl3+v+qeKJQI4pov3Cz6aNrBmBfEbjwcJrf
-RvPNCQ2X1GciZcGoJxcHRgFNKarzb+m92qNRftr6YDBZM8PlvJgGhnTRkOuFmIZB
-WPRergEwaClp1DbQsXwKlWpGfSMLznj57oKT3MJ31R4pusfMDBS39p9jUFH7uO+p
-e/Wdy+RaKei4AYBZIc+ks8LJzeIG+YWD9kN0lPVvzoza6nJYGGNVe/bxErjpESsR
-fZDs5EMNPGsCQ56Tgt+vtHEGF3x7ufGMF1XqisCMlaxH03aT2N3Wi5um8jO2pfFC
-4NEBq4ixvlyefb0TER+5AoIBAQC6nSDDzeeseLOJ8QSb1kHHkvQOGb8kdYY/KJ51
-+uiwoEWOYAxKubqumo2rYaqcM0lbZKWb/9cgVK4LAzdqY4z3BINA7YRzXSUXdb8T
-rbqtg33Yj7f1KBiBqns2FMktfIZ+6JUDALb+CD7rHGpi62RDd8JaKL8wugqMBmwM
-YHBfzECVSjDosjGpbILbDJPTfiEQLyPEoJxJ48Z3Xg6l+0BSZrrH9FqGVgsvEQ7f
-zhZ6rpJIefb1cFjwIRFORS4tMqS1keu+dugyUBs83AOp5kaq6O31n5hDAOyZVFsw
-HSBu8pbWAceWJrF7R1Am23063hIztjPbU9yeN2mvhVQSgO4PAoIBAQDnBQHt3prI
-AajCYbHmk0v1WT2kDD5yEX/fZzifTU5k/+0Jvixpa0KOR2qaUXyx4ocIT6F1hR89
-VXGby2UG6SlvuwXMzwmoVf5sueQ6wshu3fCaS8BYNpJnOAfgLTnUpKIWITDm/2Hj
-4NCFYL77EfBXXhFH7lLPhiPcTWQlPDuFCXU/BJuVhJbpd+GtF1+loiNQArg9nmKb
-9Ac7ccR9UBO/XSQN1th4+yaxyGQKaiYsBqsy8SPp2ynTdGXT72LePqSUrkNsjgE7
-PkzgX0pBZw8upBXk+8ByfIaaQONRbCuMQEXj6B66szaWeR2hDfaoDOk3/w6JN93r
-yPKfk4TFNB85AoIBAGoiHVVfUOjViP7l9cIPvD+eQ3GVkRFSSfS3zE+7UQXLUWPl
-GniRYywUuIgFNvw5avowpsOvYRGBN68JuEWosq52gZO2wkK+ce8Cx5aQkwBGLZey
-PWSP1khAxmx+q+BT10ZsTvtzN6AI3ofnFFaIG/EHNqECVaKH3KHAsUjkvGSvjPeb
-R2/AkOAT1+RvJc/+Bx3mQYh99AVOJz0SYHBkEjQLOyWnwqhuXVP6dqQw2LYTfRz9
-SMhUijCgDfCfBeEs0WJ2yEX96Jdc2fDmDKtfTUe8zEGK8BUDfIzD3kzh8+VF0SWL
-w5CRFxXO/DXtVS7ayC1i7eFKs8nEKDZsNOGFNF8CggEAKXRMlFKNk7Y4gijls2pb
-Bvusg/NugSmCuKPdFTjaCGWkM0tczM3ic4V9K5PTvFfZwzQG1P++S1M5v6sPxd2x
-AcudjtLX+Mz1iq0QtzqcnMhWlFljenDQdJUpVKDI789bBn2OOOU6u5lr0YM6wfLG
-HedTUoUBdxuq860vez8DryuzTkuVX48bRWmtpVG8aAxgKctTJDt3lmSDp7cSeyoT
-YRNllNYoogzvNJew2+2QS/YmYk3DFAOvzbHlU9Jw+1BiWAutLZ2NuwPC58AxourL
-XqMzCpPiRKjzvlpGcCXo6pHd+Ld+TCI8eWPiXTQUPrOSZenuwdC0kcrNPrVJ7dkc
-gQKCAQEAmE6BTX7nn0HT859PtBlsy3rM8psihR4UYuYkTdE0+KF4hBRIP6uhMAVh
-vV6UMnt3QubKIekG14seGkwkBnEhv5reYWn/1+t3qP7qqvgndGgI2yPbzJx/cPMK
-+KKhRbBAIgkjiY6hlo+DhrNS5nuBjZS2q/NnkO4NK7qBHvpIYAnRZK9qNsT4KZm6
-EO9YlCCnoZ3EB7brNgBZkxoekZG4jTlpD0E7nTxPTF1iVWedKRfmLFxAiDaSz0eo
-9tbTaRQ6ybU6jl1hMg4aINjp4xl/ScKk51veKg5ptjpPtspIh7keJRIUz3qwhuvk
-ZJpVwCxgxAOagrQtvwdedbmvChAfGA==
------END PRIVATE KEY-----
diff --git a/biometrics/face/aidl/default/apex/com.android.hardware.biometrics.face.pk8 b/biometrics/face/aidl/default/apex/com.android.hardware.biometrics.face.pk8
deleted file mode 100644
index af0ff4e..0000000
--- a/biometrics/face/aidl/default/apex/com.android.hardware.biometrics.face.pk8
+++ /dev/null
Binary files differ
diff --git a/biometrics/face/aidl/default/apex/com.android.hardware.biometrics.face.x509.pem b/biometrics/face/aidl/default/apex/com.android.hardware.biometrics.face.x509.pem
deleted file mode 100644
index 3dc37ff..0000000
--- a/biometrics/face/aidl/default/apex/com.android.hardware.biometrics.face.x509.pem
+++ /dev/null
@@ -1,34 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIF7TCCA9UCFCmJBOOYRVUgdy8vKm8OQd0ii2pPMA0GCSqGSIb3DQEBCwUAMIGx
-MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91
-bnRhaW4gVmlldzEQMA4GA1UECgwHQW5kcm9pZDEQMA4GA1UECwwHQW5kcm9pZDEi
-MCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTEtMCsGA1UEAwwkY29t
-LmFuZHJvaWQuaGFyZHdhcmUuYmlvbWV0cmljcy5mYWNlMCAXDTIzMDUyNTA2NDIw
-MFoYDzQ3NjEwNDIwMDY0MjAwWjCBsTELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNh
-bGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxEDAOBgNVBAoMB0FuZHJv
-aWQxEDAOBgNVBAsMB0FuZHJvaWQxIjAgBgkqhkiG9w0BCQEWE2FuZHJvaWRAYW5k
-cm9pZC5jb20xLTArBgNVBAMMJGNvbS5hbmRyb2lkLmhhcmR3YXJlLmJpb21ldHJp
-Y3MuZmFjZTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAPadnCNPEvKN
-HxACZt3C+tE2rga6gZ1pxfvlwGo1UY9yAxcQjL22SW93OA6R3de5uvQUbHh7b9g5
-AbNYcRnxOMiuUK2XSGWGDscxuGpQVCph4G1rXCOtbTmz1Zb42vQLCCQHHyxzI7ZE
-9Y6+rzw4p3jtEyBSiiErk13GFZTzwcDzqsQs12vDn9ovSTTn5Nyy6Csz7+O2t4SN
-qU4S/uLE6b/TiXj7196r58DcGvJgKbzbbnv/DUHGfaESrVWYLk3xoX3X8VJvP7jI
-M9XoZBbbgFLgAP5DFEvf5QWS9tR092z0YXOGr+mLHtkJM7Or9nKOohm6aFfHbuvu
-pSWyR4FWnaFANQ8wLH+fH485fiO6juJdTuRWeQpZddv0/IgguZ2Plu7z6NHCf5+L
-KYFjQ5y716wOufIqHhRLqYnpsAG2AFaMuPKzsy2KMifqoyB4KYR24EA1MCT7vwqu
-Hurp+SJrmNdkFVXbhGVUfMKf4nRZ37b9Miie0ju0OxJ9C3zY5uR5BMnqEjqq/rCX
-pQh5o1y+bWacOQVp0iQWJHfy8KkjhhQ1Pd1VeoVk9l2DsAJWm6unwMvGHviRcvzg
-BejDOVcE0x4xDj+TwAu2X2+w2hbUSY9W6lmkX4nGHlbLz211bIBFq42PzAMpRnYq
-jLxml4VpO4UnhyRp7Ipps99s7/iMFOn7AgMBAAEwDQYJKoZIhvcNAQELBQADggIB
-AG/5t56hKYKORne0bwJpMSCWZNT6JcYjf6fEmNrvG3/gz9BCuj4osZjJHD2OSUJl
-F5yI52RgPrXK8bNqJOvX6MIc4Y2JoSI2Uz4J2vZ3QhRkPC9oqwk/Enz4GIVJ4Dnm
-/kgpBbN2SN0TjnmEooptly5tWb3IPTjqLZpaPIW1ntQeCAbgrYVHiMsvNe1BuBrn
-RNi1xqw3QGp2ZV/RfJ3MH6d49TswEL1gwiUeg3hw5eG7IDfLB/2IJBrff7kmPTQ6
-n+il4uXuXMmX70xSvJXwP/NinomJsORZ4Npbmp7xV/QJp9cNoxNAo3DJ4OHRAnA+
-L7E1KZ3+nSRxGcVlqBekmG6wH9U39NN+dh758aGdJOWqA+B+1PAGxkvFCNqLgTpm
-xNl62YiRRo4FiIAkntvs+JneMEphv/T5i824t2xFZD2lBuW8r54nWj5cpx8AU9W2
-rulR0jx7BnVdj6czn1/pPCIah8Os9pZM8q1CbF8vXD+QLAF0/NjPNomTEGd/M+V+
-sfn1OhLGF/E1kWyNeOmkvX26txQdY8k6jUdsAc5vmQqgwxdorjI38ynpYQnFwq2g
-eO4l62sx8icsSh2TRklWy8BwZpaCyO/WVv/FcjIUexYhmZ0EHpmQk/RAlD1f9wFy
-CciNa/Dm94AwJgZk9LcXye3BSvb1sKF6C7eYrW0eI95V
------END CERTIFICATE-----
diff --git a/biometrics/face/aidl/default/apex/manifest.json b/biometrics/face/aidl/default/apex/manifest.json
index 4d46896..ecdc299 100644
--- a/biometrics/face/aidl/default/apex/manifest.json
+++ b/biometrics/face/aidl/default/apex/manifest.json
@@ -1,4 +1,4 @@
 {
-    "name": "com.android.hardware.biometrics.face",
+    "name": "com.android.hardware.biometrics.face.virtual",
     "version": 1
 }
diff --git a/biometrics/face/aidl/default/face-default.rc b/biometrics/face/aidl/default/face-default.rc
deleted file mode 100644
index f6499f0..0000000
--- a/biometrics/face/aidl/default/face-default.rc
+++ /dev/null
@@ -1,5 +0,0 @@
-service vendor.face-default /vendor/bin/hw/android.hardware.biometrics.face-service.example
-    class hal
-    user nobody
-    group nobody
-
diff --git a/biometrics/face/aidl/default/face-example.rc b/biometrics/face/aidl/default/face-example.rc
new file mode 100644
index 0000000..b0d82c6
--- /dev/null
+++ b/biometrics/face/aidl/default/face-example.rc
@@ -0,0 +1,8 @@
+service vendor.face-example /vendor/bin/hw/android.hardware.biometrics.face-service.example
+    class hal
+    user nobody
+    group nobody
+    interface aidl android.hardware.biometrics.face.IFace/virtual
+    oneshot
+    disabled
+
diff --git a/biometrics/face/aidl/default/face-default.xml b/biometrics/face/aidl/default/face-example.xml
similarity index 81%
rename from biometrics/face/aidl/default/face-default.xml
rename to biometrics/face/aidl/default/face-example.xml
index 8f2fbb8..1c5071a 100644
--- a/biometrics/face/aidl/default/face-default.xml
+++ b/biometrics/face/aidl/default/face-example.xml
@@ -2,6 +2,6 @@
     <hal format="aidl">
         <name>android.hardware.biometrics.face</name>
         <version>3</version>
-        <fqname>IFace/default</fqname>
+        <fqname>IFace/virtual</fqname>
     </hal>
 </manifest>
diff --git a/biometrics/face/aidl/default/face.sysprop b/biometrics/face/aidl/default/face.sysprop
index 6b0f37f..be32015 100644
--- a/biometrics/face/aidl/default/face.sysprop
+++ b/biometrics/face/aidl/default/face.sysprop
@@ -157,3 +157,22 @@
     access: ReadWrite
     api_name: "operation_authenticate_duration"
 }
+
+# insert error for authenticate operations
+prop {
+    prop_name: "vendor.face.virtual.operation_authenticate_error"
+    type: Integer
+    scope: Internal
+    access: ReadWrite
+    api_name: "operation_authenticate_error"
+}
+
+# acquired info during authentication in format of sequence
+prop {
+    prop_name: "vendor.face.virtual.operation_authenticate_acquired"
+    type: String
+    scope: Internal
+    access: ReadWrite
+    api_name: "operation_authenticate_acquired"
+}
+
diff --git a/biometrics/face/aidl/default/main.cpp b/biometrics/face/aidl/default/main.cpp
index b7274e3..38e1c63 100644
--- a/biometrics/face/aidl/default/main.cpp
+++ b/biometrics/face/aidl/default/main.cpp
@@ -27,9 +27,11 @@
     ABinderProcess_setThreadPoolMaxThreadCount(0);
     std::shared_ptr<Face> hal = ndk::SharedRefBase::make<Face>();
 
-    const std::string instance = std::string(Face::descriptor) + "/default";
-    binder_status_t status = AServiceManager_addService(hal->asBinder().get(), instance.c_str());
+    const std::string instance = std::string(Face::descriptor) + "/virtual";
+    binder_status_t status =
+            AServiceManager_registerLazyService(hal->asBinder().get(), instance.c_str());
     CHECK_EQ(status, STATUS_OK);
+    AServiceManager_forceLazyServicesPersist(true);
 
     ABinderProcess_joinThreadPool();
     return EXIT_FAILURE;  // should not reach
diff --git a/biometrics/face/aidl/default/tests/FakeFaceEngineTest.cpp b/biometrics/face/aidl/default/tests/FakeFaceEngineTest.cpp
index c8ad6b7..6897dc4 100644
--- a/biometrics/face/aidl/default/tests/FakeFaceEngineTest.cpp
+++ b/biometrics/face/aidl/default/tests/FakeFaceEngineTest.cpp
@@ -245,7 +245,7 @@
     FaceHalProperties::enrollments({3});
     FaceHalProperties::enrollment_hit(100);
     mEngine.authenticateImpl(mCallback.get(), 0 /* operationId*/, mCancel.get_future());
-    ASSERT_EQ(Error::UNABLE_TO_PROCESS, mCallback->mError);
+    ASSERT_EQ(Error::TIMEOUT, mCallback->mError);
     ASSERT_TRUE(mCallback->mAuthenticateFailed);
 }
 
@@ -380,4 +380,4 @@
     ASSERT_FALSE(mCallback->mAuthenticateFailed);
 }
 
-}  // namespace aidl::android::hardware::biometrics::face
\ No newline at end of file
+}  // namespace aidl::android::hardware::biometrics::face
diff --git a/biometrics/fingerprint/aidl/default/FakeFingerprintEngine.cpp b/biometrics/fingerprint/aidl/default/FakeFingerprintEngine.cpp
index 54076c8..4e80052 100644
--- a/biometrics/fingerprint/aidl/default/FakeFingerprintEngine.cpp
+++ b/biometrics/fingerprint/aidl/default/FakeFingerprintEngine.cpp
@@ -32,7 +32,9 @@
 namespace aidl::android::hardware::biometrics::fingerprint {
 
 FakeFingerprintEngine::FakeFingerprintEngine()
-    : mRandom(std::mt19937::default_seed), mWorkMode(WorkMode::kIdle) {}
+    : mRandom(std::mt19937::default_seed),
+      mWorkMode(WorkMode::kIdle),
+      isLockoutTimerSupported(true) {}
 
 void FakeFingerprintEngine::generateChallengeImpl(ISessionCallback* cb) {
     BEGIN_OP(0);
@@ -142,7 +144,7 @@
         return true;
     }
     auto enrollmentId = std::stoi(parts[0]);
-    auto progress = parseEnrollmentCapture(parts[1]);
+    auto progress = Util::parseEnrollmentCapture(parts[1]);
     for (size_t i = 0; i < progress.size(); i += 2) {
         auto left = (progress.size() - i) / 2 - 1;
         auto duration = progress[i][0];
@@ -193,7 +195,7 @@
     int64_t now = Util::getSystemNanoTime();
     int64_t duration = FingerprintHalProperties::operation_authenticate_duration().value_or(10);
     auto acquired = FingerprintHalProperties::operation_authenticate_acquired().value_or("1");
-    auto acquiredInfos = parseIntSequence(acquired);
+    auto acquiredInfos = Util::parseIntSequence(acquired);
     int N = acquiredInfos.size();
 
     if (N == 0) {
@@ -271,7 +273,7 @@
             FingerprintHalProperties::operation_detect_interaction_duration().value_or(10);
 
     auto acquired = FingerprintHalProperties::operation_detect_interaction_acquired().value_or("1");
-    auto acquiredInfos = parseIntSequence(acquired);
+    auto acquiredInfos = Util::parseIntSequence(acquired);
     int N = acquiredInfos.size();
     int64_t now = Util::getSystemNanoTime();
 
@@ -305,15 +307,6 @@
         SLEEP_MS(duration / N);
     } while (!Util::hasElapsed(now, duration));
 
-    auto id = FingerprintHalProperties::enrollment_hit().value_or(0);
-    auto enrolls = FingerprintHalProperties::enrollments();
-    auto isEnrolled = std::find(enrolls.begin(), enrolls.end(), id) != enrolls.end();
-    if (id <= 0 || !isEnrolled) {
-        LOG(ERROR) << "Fail: not enrolled";
-        cb->onError(Error::UNABLE_TO_PROCESS, 0 /* vendorError */);
-        return true;
-    }
-
     cb->onInteractionDetected();
 
     return true;
@@ -386,7 +379,7 @@
         return;
     }
     clearLockout(cb);
-    isLockoutTimerAborted = true;
+    if (isLockoutTimerStarted) isLockoutTimerAborted = true;
 }
 
 void FakeFingerprintEngine::clearLockout(ISessionCallback* cb) {
@@ -450,76 +443,6 @@
     return SensorLocation();
 }
 
-std::vector<int32_t> FakeFingerprintEngine::parseIntSequence(const std::string& str,
-                                                             const std::string& sep) {
-    std::vector<std::string> seqs = Util::split(str, sep);
-    std::vector<int32_t> res;
-
-    for (const auto& seq : seqs) {
-        int32_t val;
-        if (ParseInt(seq, &val)) {
-            res.push_back(val);
-        } else {
-            LOG(WARNING) << "Invalid int sequence:" + str;
-            res.clear();
-            break;
-        }
-    }
-
-    return res;
-}
-
-bool FakeFingerprintEngine::parseEnrollmentCaptureSingle(const std::string& str,
-                                                         std::vector<std::vector<int32_t>>& res) {
-    std::vector<int32_t> defaultAcquiredInfo = {(int32_t)AcquiredInfo::GOOD};
-    bool aborted = true;
-
-    do {
-        std::smatch sms;
-        // Parses strings like "1000-[5,1]" or "500"
-        std::regex ex("((\\d+)(-\\[([\\d|,]+)\\])?)");
-        if (!regex_match(str.cbegin(), str.cend(), sms, ex)) break;
-        int32_t duration;
-        if (!ParseInt(sms.str(2), &duration)) break;
-        res.push_back({duration});
-        if (!sms.str(4).empty()) {
-            auto acqv = parseIntSequence(sms.str(4));
-            if (acqv.empty()) break;
-            res.push_back(acqv);
-        } else
-            res.push_back(defaultAcquiredInfo);
-        aborted = false;
-    } while (0);
-
-    return !aborted;
-}
-
-std::vector<std::vector<int32_t>> FakeFingerprintEngine::parseEnrollmentCapture(
-        const std::string& str) {
-    std::vector<std::vector<int32_t>> res;
-
-    std::string s(str);
-    s.erase(std::remove_if(s.begin(), s.end(), ::isspace), s.end());
-    bool aborted = false;
-    std::smatch sms;
-    // Parses strings like "1000-[5,1],500,800-[6,5,1]"
-    //                      ---------- --- -----------
-    //  into parts:             A       B       C
-    while (regex_search(s, sms, std::regex("^(,)?(\\d+(-\\[[\\d|,]+\\])?)"))) {
-        if (!parseEnrollmentCaptureSingle(sms.str(2), res)) {
-            aborted = true;
-            break;
-        }
-        s = sms.suffix();
-    }
-    if (aborted || s.length() != 0) {
-        res.clear();
-        LOG(ERROR) << "Failed to parse enrollment captures:" + str;
-    }
-
-    return res;
-}
-
 std::pair<AcquiredInfo, int32_t> FakeFingerprintEngine::convertAcquiredInfo(int32_t code) {
     std::pair<AcquiredInfo, int32_t> res;
     if (code > FINGERPRINT_ACQUIRED_VENDOR_BASE) {
@@ -603,6 +526,7 @@
     isLockoutTimerStarted = true;
 }
 void FakeFingerprintEngine::lockoutTimerExpired(ISessionCallback* cb) {
+    BEGIN_OP(0);
     if (!isLockoutTimerAborted) {
         clearLockout(cb);
     }
diff --git a/biometrics/fingerprint/aidl/default/FakeFingerprintEngineSide.cpp b/biometrics/fingerprint/aidl/default/FakeFingerprintEngineSide.cpp
index a78cdcd..acb792d 100644
--- a/biometrics/fingerprint/aidl/default/FakeFingerprintEngineSide.cpp
+++ b/biometrics/fingerprint/aidl/default/FakeFingerprintEngineSide.cpp
@@ -27,9 +27,7 @@
 
 namespace aidl::android::hardware::biometrics::fingerprint {
 
-FakeFingerprintEngineSide::FakeFingerprintEngineSide() : FakeFingerprintEngine() {
-    isLockoutTimerSupported = true;
-}
+FakeFingerprintEngineSide::FakeFingerprintEngineSide() : FakeFingerprintEngine() {}
 
 SensorLocation FakeFingerprintEngineSide::defaultSensorLocation() {
     return SensorLocation{.sensorLocationX = defaultSensorLocationX,
diff --git a/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngine.h b/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngine.h
index 2450115..15d8360 100644
--- a/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngine.h
+++ b/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngine.h
@@ -68,10 +68,6 @@
 
     virtual void fingerDownAction();
 
-    std::vector<int32_t> parseIntSequence(const std::string& str, const std::string& sep = ",");
-
-    std::vector<std::vector<int32_t>> parseEnrollmentCapture(const std::string& str);
-
     int32_t getLatency(const std::vector<std::optional<std::int32_t>>& latencyVec);
 
     std::mt19937 mRandom;
@@ -110,8 +106,6 @@
     static constexpr int32_t FINGERPRINT_ERROR_VENDOR_BASE = 1000;
     std::pair<AcquiredInfo, int32_t> convertAcquiredInfo(int32_t code);
     std::pair<Error, int32_t> convertError(int32_t code);
-    bool parseEnrollmentCaptureSingle(const std::string& str,
-                                      std::vector<std::vector<int32_t>>& res);
     int32_t getRandomInRange(int32_t bound1, int32_t bound2);
     bool checkSensorLockout(ISessionCallback*);
     void clearLockout(ISessionCallback* cb);
diff --git a/biometrics/fingerprint/aidl/default/tests/FakeFingerprintEngineTest.cpp b/biometrics/fingerprint/aidl/default/tests/FakeFingerprintEngineTest.cpp
index fe405f4..eedcae1 100644
--- a/biometrics/fingerprint/aidl/default/tests/FakeFingerprintEngineTest.cpp
+++ b/biometrics/fingerprint/aidl/default/tests/FakeFingerprintEngineTest.cpp
@@ -357,7 +357,7 @@
     FingerprintHalProperties::enrollment_hit({});
     mEngine.detectInteractionImpl(mCallback.get(), mCancel.get_future());
     mEngine.fingerDownAction();
-    ASSERT_EQ(0, mCallback->mInteractionDetectedCount);
+    ASSERT_EQ(1, mCallback->mInteractionDetectedCount);
 }
 
 TEST_F(FakeFingerprintEngineTest, InteractionDetectNotEnrolled) {
@@ -365,7 +365,7 @@
     FingerprintHalProperties::enrollment_hit(25);
     mEngine.detectInteractionImpl(mCallback.get(), mCancel.get_future());
     mEngine.fingerDownAction();
-    ASSERT_EQ(0, mCallback->mInteractionDetectedCount);
+    ASSERT_EQ(1, mCallback->mInteractionDetectedCount);
 }
 
 TEST_F(FakeFingerprintEngineTest, InteractionDetectError) {
@@ -421,29 +421,29 @@
 
 TEST_F(FakeFingerprintEngineTest, parseIntSequence) {
     std::vector<int32_t> seqV;
-    seqV = mEngine.parseIntSequence("");
+    seqV = Util::parseIntSequence("");
     ASSERT_EQ(0, seqV.size());
-    seqV = mEngine.parseIntSequence("2");
+    seqV = Util::parseIntSequence("2");
     ASSERT_EQ(1, seqV.size());
     ASSERT_EQ(2, seqV[0]);
-    seqV = mEngine.parseIntSequence("2,3,4");
+    seqV = Util::parseIntSequence("2,3,4");
     std::vector<int32_t> expV{2, 3, 4};
     ASSERT_EQ(expV, seqV);
-    seqV = mEngine.parseIntSequence("2,3,a");
+    seqV = Util::parseIntSequence("2,3,a");
     ASSERT_EQ(0, seqV.size());
-    seqV = mEngine.parseIntSequence("2, 3, 4");
+    seqV = Util::parseIntSequence("2, 3, 4");
     ASSERT_EQ(expV, seqV);
-    seqV = mEngine.parseIntSequence("123,456");
+    seqV = Util::parseIntSequence("123,456");
     ASSERT_EQ(2, seqV.size());
     std::vector<int32_t> expV1{123, 456};
     ASSERT_EQ(expV1, seqV);
-    seqV = mEngine.parseIntSequence("12f3,456");
+    seqV = Util::parseIntSequence("12f3,456");
     ASSERT_EQ(0, seqV.size());
 }
 
 TEST_F(FakeFingerprintEngineTest, parseEnrollmentCaptureOk) {
     std::vector<std::vector<int32_t>> ecV;
-    ecV = mEngine.parseEnrollmentCapture("100,200,300");
+    ecV = Util::parseEnrollmentCapture("100,200,300");
     ASSERT_EQ(6, ecV.size());
     std::vector<std::vector<int32_t>> expE{{100}, {200}, {300}};
     std::vector<int32_t> defC{1};
@@ -451,26 +451,26 @@
         ASSERT_EQ(expE[i / 2], ecV[i]);
         ASSERT_EQ(defC, ecV[i + 1]);
     }
-    ecV = mEngine.parseEnrollmentCapture("100");
+    ecV = Util::parseEnrollmentCapture("100");
     ASSERT_EQ(2, ecV.size());
     ASSERT_EQ(expE[0], ecV[0]);
     ASSERT_EQ(defC, ecV[1]);
 
-    ecV = mEngine.parseEnrollmentCapture("100-[5,6,7]");
+    ecV = Util::parseEnrollmentCapture("100-[5,6,7]");
     std::vector<int32_t> expC{5, 6, 7};
     ASSERT_EQ(2, ecV.size());
     for (int i = 0; i < ecV.size(); i += 2) {
         ASSERT_EQ(expE[i / 2], ecV[i]);
         ASSERT_EQ(expC, ecV[i + 1]);
     }
-    ecV = mEngine.parseEnrollmentCapture("100-[5,6,7], 200, 300-[9,10]");
+    ecV = Util::parseEnrollmentCapture("100-[5,6,7], 200, 300-[9,10]");
     std::vector<std::vector<int32_t>> expC1{{5, 6, 7}, {1}, {9, 10}};
     ASSERT_EQ(6, ecV.size());
     for (int i = 0; i < ecV.size(); i += 2) {
         ASSERT_EQ(expE[i / 2], ecV[i]);
         ASSERT_EQ(expC1[i / 2], ecV[i + 1]);
     }
-    ecV = mEngine.parseEnrollmentCapture("100-[5,6,7], 200-[2,1], 300-[9]");
+    ecV = Util::parseEnrollmentCapture("100-[5,6,7], 200-[2,1], 300-[9]");
     std::vector<std::vector<int32_t>> expC2{{5, 6, 7}, {2, 1}, {9}};
     ASSERT_EQ(ecV.size(), 6);
     for (int i = 0; i < ecV.size(); i += 2) {
@@ -484,7 +484,7 @@
                                     "100,2x0,300", "200-[f]", "a,b"};
     std::vector<std::vector<int32_t>> ecV;
     for (const auto& s : badStr) {
-        ecV = mEngine.parseEnrollmentCapture(s);
+        ecV = Util::parseEnrollmentCapture(s);
         ASSERT_EQ(ecV.size(), 0);
     }
 }
@@ -508,7 +508,7 @@
 TEST_F(FakeFingerprintEngineTest, lockoutTimer) {
     mEngine.startLockoutTimer(200, mCallback.get());
     ASSERT_TRUE(mEngine.getLockoutTimerStarted());
-    std::this_thread::sleep_for(std::chrono::milliseconds(210));
+    std::this_thread::sleep_for(std::chrono::milliseconds(250));
     ASSERT_FALSE(mEngine.getLockoutTimerStarted());
     ASSERT_TRUE(mCallback->mLockoutCleared);
 }
diff --git a/bluetooth/audio/utils/aidl_session/BluetoothAudioCodecs.cpp b/bluetooth/audio/utils/aidl_session/BluetoothAudioCodecs.cpp
index 3ed9e07..b4cba49 100644
--- a/bluetooth/audio/utils/aidl_session/BluetoothAudioCodecs.cpp
+++ b/bluetooth/audio/utils/aidl_session/BluetoothAudioCodecs.cpp
@@ -20,8 +20,6 @@
 
 #include <aidl/android/hardware/bluetooth/audio/AacCapabilities.h>
 #include <aidl/android/hardware/bluetooth/audio/AacObjectType.h>
-#include <aidl/android/hardware/bluetooth/audio/AptxAdaptiveLeCapabilities.h>
-#include <aidl/android/hardware/bluetooth/audio/AptxAdaptiveLeConfiguration.h>
 #include <aidl/android/hardware/bluetooth/audio/AptxCapabilities.h>
 #include <aidl/android/hardware/bluetooth/audio/ChannelMode.h>
 #include <aidl/android/hardware/bluetooth/audio/LdacCapabilities.h>
@@ -100,55 +98,6 @@
 
 std::vector<LeAudioCodecCapabilitiesSetting> kDefaultOffloadLeAudioCapabilities;
 
-static const UnicastCapability kInvalidUnicastCapability = {
-    .codecType = CodecType::UNKNOWN};
-
-static const AptxAdaptiveLeCapabilities
-    kDefaultOffloadAptxAdaptiveLeCapability_48k = {
-        .samplingFrequencyHz = {48000},
-        .frameDurationUs = {10000},
-        .octetsPerFrame = {816}};
-
-static const AptxAdaptiveLeCapabilities
-    kDefaultOffloadAptxAdaptiveLeCapability_96k = {
-        .samplingFrequencyHz = {96000},
-        .frameDurationUs = {10000},
-        .octetsPerFrame = {816}};
-
-static const AptxAdaptiveLeCapabilities
-    kDefaultOffloadAptxAdaptiveLeXCapability_48k = {
-        .samplingFrequencyHz = {48000},
-        .frameDurationUs = {10000},
-        .octetsPerFrame = {816}};
-
-static const AptxAdaptiveLeCapabilities
-    kDefaultOffloadAptxAdaptiveLeXCapability_96k = {
-        .samplingFrequencyHz = {96000},
-        .frameDurationUs = {10000},
-        .octetsPerFrame = {816}};
-
-static const BroadcastCapability kInvalidBroadcastCapability = {
-    .codecType = CodecType::UNKNOWN};
-
-static AudioLocation stereoAudio = static_cast<AudioLocation>(
-    static_cast<uint8_t>(AudioLocation::FRONT_LEFT) |
-    static_cast<uint8_t>(AudioLocation::FRONT_RIGHT));
-
-static const std::vector<AptxAdaptiveLeCapabilities>
-    supportedAptxAdaptiveLeCapabilityList = {
-        kDefaultOffloadAptxAdaptiveLeCapability_48k,
-        kDefaultOffloadAptxAdaptiveLeCapability_96k,
-        kDefaultOffloadAptxAdaptiveLeXCapability_48k,
-        kDefaultOffloadAptxAdaptiveLeXCapability_96k};
-
-// Stores the supported setting of audio location, connected device, and the
-// channel count for each device
-std::vector<std::tuple<AudioLocation, uint8_t, uint8_t>>
-    supportedDeviceSetting = {
-        // Stereo, one connected device for both L and R
-        std::make_tuple(stereoAudio, 1, 2),
-};
-
 template <class T>
 bool BluetoothAudioCodecs::ContainedInVector(
     const std::vector<T>& vector, const typename identity<T>::type& target) {
@@ -458,32 +407,6 @@
     kDefaultOffloadLeAudioCapabilities =
         BluetoothLeAudioCodecsProvider::GetLeAudioCodecCapabilities(
             le_audio_offload_setting);
-
-    for (auto [audioLocation, deviceCnt, channelCount] :
-         supportedDeviceSetting) {
-      for (auto capability : supportedAptxAdaptiveLeCapabilityList) {
-        for (auto codec_type :
-             {CodecType::APTX_ADAPTIVE_LE, CodecType::APTX_ADAPTIVE_LEX}) {
-          if (session_type ==
-              SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH) {
-            UnicastCapability aptx_adaptive_le_cap = {
-                .codecType = codec_type,
-                .supportedChannel = audioLocation,
-                .deviceCount = deviceCnt,
-                .channelCountPerDevice = channelCount,
-                .leAudioCodecCapabilities =
-                    UnicastCapability::LeAudioCodecCapabilities(capability),
-            };
-
-            // Adds the capability for encode only
-            kDefaultOffloadLeAudioCapabilities.push_back(
-                {.unicastEncodeCapability = aptx_adaptive_le_cap,
-                 .unicastDecodeCapability = kInvalidUnicastCapability,
-                 .broadcastCapability = kInvalidBroadcastCapability});
-          }
-        }
-      }
-    }
   }
   return kDefaultOffloadLeAudioCapabilities;
 }
diff --git a/bluetooth/audio/utils/aidl_session/BluetoothLeAudioCodecsProvider.cpp b/bluetooth/audio/utils/aidl_session/BluetoothLeAudioCodecsProvider.cpp
index 0a804bb..26da5fb 100644
--- a/bluetooth/audio/utils/aidl_session/BluetoothLeAudioCodecsProvider.cpp
+++ b/bluetooth/audio/utils/aidl_session/BluetoothLeAudioCodecsProvider.cpp
@@ -256,6 +256,15 @@
         strategy_configuration_iter->second.getConnectedDevice(),
         strategy_configuration_iter->second.getChannelCount(),
         ComposeLc3Capability(codec_configuration_iter->second));
+  } else if (codec_type == CodecType::APTX_ADAPTIVE_LE ||
+             codec_type == CodecType::APTX_ADAPTIVE_LEX) {
+    return ComposeUnicastCapability(
+        codec_type,
+        GetAudioLocation(
+            strategy_configuration_iter->second.getAudioLocation()),
+        strategy_configuration_iter->second.getConnectedDevice(),
+        strategy_configuration_iter->second.getChannelCount(),
+        ComposeAptxAdaptiveLeCapability(codec_configuration_iter->second));
   }
   return {.codecType = CodecType::UNKNOWN};
 }
@@ -330,6 +339,14 @@
           .octetsPerFrame = {codec_configuration.getOctetsPerCodecFrame()}};
 }
 
+AptxAdaptiveLeCapabilities
+BluetoothLeAudioCodecsProvider::ComposeAptxAdaptiveLeCapability(
+    const setting::CodecConfiguration& codec_configuration) {
+  return {.samplingFrequencyHz = {codec_configuration.getSamplingFrequency()},
+          .frameDurationUs = {codec_configuration.getFrameDurationUs()},
+          .octetsPerFrame = {codec_configuration.getOctetsPerCodecFrame()}};
+}
+
 AudioLocation BluetoothLeAudioCodecsProvider::GetAudioLocation(
     const setting::AudioLocation& audio_location) {
   switch (audio_location) {
@@ -347,6 +364,10 @@
   switch (codec_type) {
     case setting::CodecType::LC3:
       return CodecType::LC3;
+    case setting::CodecType::APTX_ADAPTIVE_LE:
+      return CodecType::APTX_ADAPTIVE_LE;
+    case setting::CodecType::APTX_ADAPTIVE_LEX:
+      return CodecType::APTX_ADAPTIVE_LEX;
     default:
       return CodecType::UNKNOWN;
   }
diff --git a/bluetooth/audio/utils/aidl_session/BluetoothLeAudioCodecsProvider.h b/bluetooth/audio/utils/aidl_session/BluetoothLeAudioCodecsProvider.h
index 06e4595..654e70c 100644
--- a/bluetooth/audio/utils/aidl_session/BluetoothLeAudioCodecsProvider.h
+++ b/bluetooth/audio/utils/aidl_session/BluetoothLeAudioCodecsProvider.h
@@ -84,6 +84,9 @@
   static inline Lc3Capabilities ComposeLc3Capability(
       const setting::CodecConfiguration& codec_configuration);
 
+  static inline AptxAdaptiveLeCapabilities ComposeAptxAdaptiveLeCapability(
+      const setting::CodecConfiguration& codec_configuration);
+
   static inline AudioLocation GetAudioLocation(
       const setting::AudioLocation& audio_location);
   static inline CodecType GetCodecType(const setting::CodecType& codec_type);
diff --git a/bluetooth/audio/utils/le_audio_codec_capabilities/le_audio_codec_capabilities.xml b/bluetooth/audio/utils/le_audio_codec_capabilities/le_audio_codec_capabilities.xml
index c8d1af0..eaace78 100644
--- a/bluetooth/audio/utils/le_audio_codec_capabilities/le_audio_codec_capabilities.xml
+++ b/bluetooth/audio/utils/le_audio_codec_capabilities/le_audio_codec_capabilities.xml
@@ -31,6 +31,10 @@
     <scenario encode="OneChanMono_16_2" decode="invalid"/>
     <scenario encode="TwoChanStereo_16_2" decode="invalid"/>
     <scenario encode="OneChanStereo_16_2" decode="invalid"/>
+    <scenario encode="APEX_ADAPTIVE_LE_TwoChanStereo_48" decode="invalid"/>
+    <scenario encode="APEX_ADAPTIVE_LE_TwoChanStereo_96" decode="invalid"/>
+    <scenario encode="APEX_ADAPTIVE_LEX_TwoChanStereo_48" decode="invalid"/>
+    <scenario encode="APEX_ADAPTIVE_LEX_TwoChanStereo_96" decode="invalid"/>
     <!-- encode and decode -->
     <scenario encode="OneChanStereo_16_1" decode="OneChanStereo_16_1"/>
     <scenario encode="OneChanStereo_16_1" decode="OneChanMono_16_1"/>
@@ -51,10 +55,18 @@
     <configuration name="TwoChanStereo_16_2" codecConfiguration="LC3_16k_2" strategyConfiguration="STEREO_TWO_CISES_PER_DEVICE"/>
     <configuration name="OneChanStereo_16_2" codecConfiguration="LC3_16k_2" strategyConfiguration="STEREO_ONE_CIS_PER_DEVICE"/>
     <configuration name="BcastStereo_16_2" codecConfiguration="LC3_16k_2" strategyConfiguration="BROADCAST_STEREO"/>
+    <configuration name="APEX_ADAPTIVE_LE_TwoChanStereo_48" codecConfiguration="APTX_ADAPTIVE_LE_48k" strategyConfiguration="STEREO_TWO_CISES_PER_DEVICE"/>
+    <configuration name="APEX_ADAPTIVE_LE_TwoChanStereo_96" codecConfiguration="APTX_ADAPTIVE_LE_96k" strategyConfiguration="STEREO_TWO_CISES_PER_DEVICE"/>
+    <configuration name="APEX_ADAPTIVE_LEX_TwoChanStereo_48" codecConfiguration="APTX_ADAPTIVE_LEX_48k" strategyConfiguration="STEREO_TWO_CISES_PER_DEVICE"/>
+    <configuration name="APEX_ADAPTIVE_LEX_TwoChanStereo_96" codecConfiguration="APTX_ADAPTIVE_LEX_96k" strategyConfiguration="STEREO_TWO_CISES_PER_DEVICE"/>
   </configurationList>
   <codecConfigurationList>
     <codecConfiguration name="LC3_16k_1" codec="LC3" samplingFrequency="16000" frameDurationUs="7500" octetsPerCodecFrame="30"/>
     <codecConfiguration name="LC3_16k_2" codec="LC3" samplingFrequency="16000" frameDurationUs="10000" octetsPerCodecFrame="40"/>
+    <codecConfiguration name="APTX_ADAPTIVE_LE_48k" codec="APTX_ADAPTIVE_LE" samplingFrequency="48000" frameDurationUs="10000" octetsPerCodecFrame="816"/>
+    <codecConfiguration name="APTX_ADAPTIVE_LE_96k" codec="APTX_ADAPTIVE_LE" samplingFrequency="96000" frameDurationUs="10000" octetsPerCodecFrame="816"/>
+    <codecConfiguration name="APTX_ADAPTIVE_LEX_48k" codec="APTX_ADAPTIVE_LEX" samplingFrequency="48000" frameDurationUs="10000" octetsPerCodecFrame="816"/>
+    <codecConfiguration name="APTX_ADAPTIVE_LEX_96k" codec="APTX_ADAPTIVE_LEX" samplingFrequency="96000" frameDurationUs="10000" octetsPerCodecFrame="816"/>
   </codecConfigurationList>
   <strategyConfigurationList>
     <strategyConfiguration name="STEREO_ONE_CIS_PER_DEVICE" audioLocation="STEREO" connectedDevice="2" channelCount="1"/>
diff --git a/bluetooth/audio/utils/le_audio_codec_capabilities/le_audio_codec_capabilities.xsd b/bluetooth/audio/utils/le_audio_codec_capabilities/le_audio_codec_capabilities.xsd
index 8c2d6a1..03c8ade 100644
--- a/bluetooth/audio/utils/le_audio_codec_capabilities/le_audio_codec_capabilities.xsd
+++ b/bluetooth/audio/utils/le_audio_codec_capabilities/le_audio_codec_capabilities.xsd
@@ -70,6 +70,8 @@
   <xs:simpleType name="codecType">
     <xs:restriction base="xs:string">
       <xs:enumeration value="LC3"/>
+      <xs:enumeration value="APTX_ADAPTIVE_LE"/>
+      <xs:enumeration value="APTX_ADAPTIVE_LEX"/>
     </xs:restriction>
   </xs:simpleType>
 </xs:schema>
diff --git a/bluetooth/audio/utils/le_audio_codec_capabilities/schema/current.txt b/bluetooth/audio/utils/le_audio_codec_capabilities/schema/current.txt
index 3cef417..a882174 100644
--- a/bluetooth/audio/utils/le_audio_codec_capabilities/schema/current.txt
+++ b/bluetooth/audio/utils/le_audio_codec_capabilities/schema/current.txt
@@ -32,6 +32,8 @@
 
   public enum CodecType {
     method public String getRawName();
+    enum_constant public static final aidl.android.hardware.bluetooth.audio.setting.CodecType APTX_ADAPTIVE_LE;
+    enum_constant public static final aidl.android.hardware.bluetooth.audio.setting.CodecType APTX_ADAPTIVE_LEX;
     enum_constant public static final aidl.android.hardware.bluetooth.audio.setting.CodecType LC3;
   }
 
diff --git a/boot/1.0/vts/functional/OWNERS b/boot/1.0/vts/functional/OWNERS
deleted file mode 100644
index 5aeb4df..0000000
--- a/boot/1.0/vts/functional/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 1014951
-dvander@google.com
diff --git a/boot/1.1/default/Android.bp b/boot/1.1/default/Android.bp
index 0b0a5b7..e7a8d6e 100644
--- a/boot/1.1/default/Android.bp
+++ b/boot/1.1/default/Android.bp
@@ -20,6 +20,7 @@
     srcs: ["BootControl.cpp"],
 
     shared_libs: [
+        "libbase",
         "liblog",
         "libhidlbase",
         "libhardware",
diff --git a/boot/1.1/default/boot_control/Android.bp b/boot/1.1/default/boot_control/Android.bp
index 6aa30c2..d0dcb59 100644
--- a/boot/1.1/default/boot_control/Android.bp
+++ b/boot/1.1/default/boot_control/Android.bp
@@ -35,14 +35,13 @@
     ],
 
     shared_libs: [
-        "android.hardware.boot@1.1",
-        "libbase",
         "liblog",
     ],
     static_libs: [
         "libbootloader_message",
         "libfstab",
     ],
+
 }
 
 cc_library_static {
@@ -52,7 +51,13 @@
     recovery_available: true,
     vendor_available: true,
 
-    srcs: ["libboot_control.cpp"],
+    srcs: [
+        "libboot_control.cpp",
+    ],
+    static_libs: [
+        "android.hardware.boot@1.1",
+        "libbase",
+    ],
 }
 
 cc_library_shared {
@@ -67,6 +72,8 @@
         "libboot_control",
     ],
     shared_libs: [
+        "android.hardware.boot@1.1",
+        "libbase",
         "libhardware",
     ],
 }
diff --git a/boot/1.1/vts/functional/OWNERS b/boot/1.1/vts/functional/OWNERS
deleted file mode 100644
index 5aeb4df..0000000
--- a/boot/1.1/vts/functional/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 1014951
-dvander@google.com
diff --git a/boot/1.2/default/Android.bp b/boot/1.2/default/Android.bp
index 4e1c35e..f1e9c34 100644
--- a/boot/1.2/default/Android.bp
+++ b/boot/1.2/default/Android.bp
@@ -20,6 +20,7 @@
     srcs: ["BootControl.cpp"],
 
     shared_libs: [
+        "libbase",
         "liblog",
         "libhidlbase",
         "libhardware",
diff --git a/boot/aidl/vts/functional/OWNERS b/boot/OWNERS
similarity index 70%
rename from boot/aidl/vts/functional/OWNERS
rename to boot/OWNERS
index c67d246..fca3dff 100644
--- a/boot/aidl/vts/functional/OWNERS
+++ b/boot/OWNERS
@@ -1,2 +1,4 @@
 # Bug component: 1014951
+
+dvander@google.com
 zhangkelvin@google.com
diff --git a/boot/aidl/default/Android.bp b/boot/aidl/default/Android.bp
index dcb40db..c1d3c57 100644
--- a/boot/aidl/default/Android.bp
+++ b/boot/aidl/default/Android.bp
@@ -27,7 +27,39 @@
     name: "android.hardware.boot-service_common",
     relative_install_path: "hw",
     defaults: ["libboot_control_defaults"],
+    srcs: [
+        "main.cpp",
+        "BootControl.cpp",
+    ],
+}
+
+cc_binary {
+    name: "android.hardware.boot-service.default",
+    defaults: ["android.hardware.boot-service_common"],
+    vendor: true,
+
+    stl: "c++_static",
+    shared_libs: [
+        "libbinder_ndk",
+        "liblog",
+    ],
+    static_libs: [
+        "android.hardware.boot@1.1",
+        "android.hardware.boot-V1-ndk",
+        "libbase",
+        "libboot_control",
+    ],
+
+    installable: false, // installed in APEX
+}
+
+cc_binary {
+    name: "android.hardware.boot-service.default_recovery",
+    defaults: ["android.hardware.boot-service_common"],
+    init_rc: ["android.hardware.boot-service.default_recovery.rc"],
     vintf_fragments: ["android.hardware.boot-service.default.xml"],
+    recovery: true,
+
     shared_libs: [
         "libbase",
         "libbinder_ndk",
@@ -37,19 +69,35 @@
     static_libs: [
         "libboot_control",
     ],
-    srcs: ["main.cpp", "BootControl.cpp"],
 }
 
-cc_binary {
-    name: "android.hardware.boot-service.default",
-    defaults: ["android.hardware.boot-service_common"],
-    init_rc: ["android.hardware.boot-service.default.rc"],
+prebuilt_etc {
+    name: "android.hardware.boot-service.default.rc",
+    src: "android.hardware.boot-service.default.rc",
+    installable: false,
+}
+
+prebuilt_etc {
+    name: "android.hardware.boot-service.default.xml",
+    src: "android.hardware.boot-service.default.xml",
+    sub_dir: "vintf",
+    installable: false,
+}
+
+apex {
+    name: "com.android.hardware.boot",
     vendor: true,
-}
+    manifest: "apex_manifest.json",
+    file_contexts: "apex_file_contexts",
+    key: "com.android.hardware.key",
+    certificate: ":com.android.hardware.certificate",
+    updatable: false,
 
-cc_binary {
-    name: "android.hardware.boot-service.default_recovery",
-    defaults: ["android.hardware.boot-service_common"],
-    init_rc: ["android.hardware.boot-service.default_recovery.rc"],
-    recovery: true,
+    binaries: [
+        "android.hardware.boot-service.default",
+    ],
+    prebuilts: [
+        "android.hardware.boot-service.default.rc",
+        "android.hardware.boot-service.default.xml",
+    ],
 }
diff --git a/boot/aidl/default/android.hardware.boot-service.default.rc b/boot/aidl/default/android.hardware.boot-service.default.rc
index 589f803..5090e2c 100644
--- a/boot/aidl/default/android.hardware.boot-service.default.rc
+++ b/boot/aidl/default/android.hardware.boot-service.default.rc
@@ -1,4 +1,4 @@
-service vendor.boot-default /vendor/bin/hw/android.hardware.boot-service.default
+service vendor.boot-default /apex/com.android.hardware.boot/bin/hw/android.hardware.boot-service.default
     class early_hal
     user root
     group root
diff --git a/boot/aidl/default/apex_file_contexts b/boot/aidl/default/apex_file_contexts
new file mode 100644
index 0000000..bf03585
--- /dev/null
+++ b/boot/aidl/default/apex_file_contexts
@@ -0,0 +1,3 @@
+(/.*)?                                                          u:object_r:vendor_file:s0
+/etc(/.*)?                                                      u:object_r:vendor_configs_file:s0
+/bin/hw/android\.hardware\.boot-service\.default                u:object_r:hal_bootctl_default_exec:s0
diff --git a/boot/aidl/default/apex_manifest.json b/boot/aidl/default/apex_manifest.json
new file mode 100644
index 0000000..92661c9
--- /dev/null
+++ b/boot/aidl/default/apex_manifest.json
@@ -0,0 +1,5 @@
+{
+    "name": "com.android.hardware.boot",
+    "version": 1,
+    "vendorBootstrap": true
+}
\ No newline at end of file
diff --git a/broadcastradio/1.0/default/OWNERS b/broadcastradio/1.0/default/OWNERS
deleted file mode 100644
index 302fdd7..0000000
--- a/broadcastradio/1.0/default/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-xuweilin@google.com
-oscarazu@google.com
-ericjeong@google.com
-keunyoung@google.com
diff --git a/broadcastradio/1.0/vts/functional/OWNERS b/broadcastradio/1.0/vts/functional/OWNERS
deleted file mode 100644
index aa19d6a..0000000
--- a/broadcastradio/1.0/vts/functional/OWNERS
+++ /dev/null
@@ -1,5 +0,0 @@
-# Bug component: 533946
-xuweilin@google.com
-oscarazu@google.com
-ericjeong@google.com
-keunyoung@google.com
diff --git a/broadcastradio/1.1/default/OWNERS b/broadcastradio/1.1/default/OWNERS
deleted file mode 100644
index 259b91e..0000000
--- a/broadcastradio/1.1/default/OWNERS
+++ /dev/null
@@ -1,5 +0,0 @@
-# Automotive team
-xuweilin@google.com
-oscarazu@google.com
-ericjeong@google.com
-keunyoung@google.com
diff --git a/broadcastradio/2.0/default/OWNERS b/broadcastradio/2.0/default/OWNERS
deleted file mode 100644
index 259b91e..0000000
--- a/broadcastradio/2.0/default/OWNERS
+++ /dev/null
@@ -1,5 +0,0 @@
-# Automotive team
-xuweilin@google.com
-oscarazu@google.com
-ericjeong@google.com
-keunyoung@google.com
diff --git a/broadcastradio/2.0/vts/OWNERS b/broadcastradio/2.0/vts/OWNERS
deleted file mode 100644
index 09690ef..0000000
--- a/broadcastradio/2.0/vts/OWNERS
+++ /dev/null
@@ -1,8 +0,0 @@
-# Automotive team
-xuweilin@google.com
-oscarazu@google.com
-ericjeong@google.com
-keunyoung@google.com
-
-# VTS team
-dshi@google.com
diff --git a/broadcastradio/2.0/vts/functional/OWNERS b/broadcastradio/2.0/vts/functional/OWNERS
deleted file mode 100644
index aa19d6a..0000000
--- a/broadcastradio/2.0/vts/functional/OWNERS
+++ /dev/null
@@ -1,5 +0,0 @@
-# Bug component: 533946
-xuweilin@google.com
-oscarazu@google.com
-ericjeong@google.com
-keunyoung@google.com
diff --git a/broadcastradio/1.1/vts/OWNERS b/broadcastradio/OWNERS
similarity index 80%
rename from broadcastradio/1.1/vts/OWNERS
rename to broadcastradio/OWNERS
index aa19d6a..7c6aaca 100644
--- a/broadcastradio/1.1/vts/OWNERS
+++ b/broadcastradio/OWNERS
@@ -1,5 +1,5 @@
 # Bug component: 533946
-xuweilin@google.com
-oscarazu@google.com
+
 ericjeong@google.com
-keunyoung@google.com
+oscarazu@google.com
+xuweilin@google.com
diff --git a/broadcastradio/aidl/android/hardware/broadcastradio/ProgramIdentifier.aidl b/broadcastradio/aidl/android/hardware/broadcastradio/ProgramIdentifier.aidl
index 2057d97..a2de5d6 100644
--- a/broadcastradio/aidl/android/hardware/broadcastradio/ProgramIdentifier.aidl
+++ b/broadcastradio/aidl/android/hardware/broadcastradio/ProgramIdentifier.aidl
@@ -30,8 +30,10 @@
     IdentifierType type = IdentifierType.INVALID;
 
     /**
-     * The uint64_t value field holds the value in format described in comments
-     * for IdentifierType enum.
+     * The value field holds the value in format described in comments for IdentifierType enum.
+     *
+     * The value should be 64-bit unsigned integer, but is represented as 64-bit signed integer
+     * in AIDL.
      */
     long value;
 }
diff --git a/broadcastradio/aidl/default/VirtualRadio.cpp b/broadcastradio/aidl/default/VirtualRadio.cpp
index 126bcff..86c5a96 100644
--- a/broadcastradio/aidl/default/VirtualRadio.cpp
+++ b/broadcastradio/aidl/default/VirtualRadio.cpp
@@ -53,18 +53,18 @@
     static VirtualRadio amFmRadioMock(
         "AM/FM radio mock",
         {
-            {makeSelectorAmfm(/* frequency= */ 94900), "Wild 94.9", "Drake ft. Rihanna",
+            {makeSelectorAmfm(/* frequency= */ 94900u), "Wild 94.9", "Drake ft. Rihanna",
                 "Too Good"},
-            {makeSelectorAmfm(/* frequency= */ 96500), "KOIT", "Celine Dion", "All By Myself"},
-            {makeSelectorAmfm(/* frequency= */ 97300), "Alice@97.3", "Drops of Jupiter", "Train"},
-            {makeSelectorAmfm(/* frequency= */ 99700), "99.7 Now!", "The Chainsmokers", "Closer"},
-            {makeSelectorAmfm(/* frequency= */ 101300), "101-3 KISS-FM", "Justin Timberlake",
+            {makeSelectorAmfm(/* frequency= */ 96500u), "KOIT", "Celine Dion", "All By Myself"},
+            {makeSelectorAmfm(/* frequency= */ 97300u), "Alice@97.3", "Drops of Jupiter", "Train"},
+            {makeSelectorAmfm(/* frequency= */ 99700u), "99.7 Now!", "The Chainsmokers", "Closer"},
+            {makeSelectorAmfm(/* frequency= */ 101300u), "101-3 KISS-FM", "Justin Timberlake",
                 "Rock Your Body"},
-            {makeSelectorAmfm(/* frequency= */ 103700), "iHeart80s @ 103.7", "Michael Jackson",
+            {makeSelectorAmfm(/* frequency= */ 103700u), "iHeart80s @ 103.7", "Michael Jackson",
                 "Billie Jean"},
-            {makeSelectorAmfm(/* frequency= */ 106100), "106 KMEL", "Drake", "Marvins Room"},
-            {makeSelectorAmfm(/* frequency= */ 700), "700 AM", "Artist700", "Title700"},
-            {makeSelectorAmfm(/* frequency= */ 1700), "1700 AM", "Artist1700", "Title1700"},
+            {makeSelectorAmfm(/* frequency= */ 106100u), "106 KMEL", "Drake", "Marvins Room"},
+            {makeSelectorAmfm(/* frequency= */ 700u), "700 AM", "Artist700", "Title700"},
+            {makeSelectorAmfm(/* frequency= */ 1700u), "1700 AM", "Artist1700", "Title1700"},
         });
     // clang-format on
     return amFmRadioMock;
@@ -77,13 +77,13 @@
         "DAB radio mock",
         {
             {makeSelectorDab(/* sidExt= */ 0xA000000001u, /* ensemble= */ 0x0001u,
-                /* freq= */ 225648), "BBC Radio 1", "Khalid", "Talk"},
+                /* freq= */ 225648u), "BBC Radio 1", "Khalid", "Talk"},
             {makeSelectorDab(/* sidExt= */ 0xB000000001u, /* ensemble= */ 0x1001u,
-                /* freq= */ 222064), "Classic FM", "Jean Sibelius", "Andante Festivo"},
+                /* freq= */ 222064u), "Classic FM", "Jean Sibelius", "Andante Festivo"},
             {makeSelectorDab(/* sidExt= */ 0xB000000002u, /* ensemble= */ 0x1002u,
-                /* freq= */ 227360), "Absolute Radio", "Coldplay", "Clocks"},
+                /* freq= */ 227360u), "Absolute Radio", "Coldplay", "Clocks"},
             {makeSelectorDab(/* sidExt= */ 0xB000000002u, /* ensemble= */ 0x1002u,
-                /* freq= */ 222064), "Absolute Radio", "Coldplay", "Clocks"},
+                /* freq= */ 222064u), "Absolute Radio", "Coldplay", "Clocks"},
         });
     // clang-format on
     return dabRadioMock;
diff --git a/broadcastradio/common/OWNERS b/broadcastradio/common/OWNERS
deleted file mode 100644
index 259b91e..0000000
--- a/broadcastradio/common/OWNERS
+++ /dev/null
@@ -1,5 +0,0 @@
-# Automotive team
-xuweilin@google.com
-oscarazu@google.com
-ericjeong@google.com
-keunyoung@google.com
diff --git a/broadcastradio/common/utilsaidl/Utils.cpp b/broadcastradio/common/utilsaidl/Utils.cpp
index 0551bad..de4f529 100644
--- a/broadcastradio/common/utilsaidl/Utils.cpp
+++ b/broadcastradio/common/utilsaidl/Utils.cpp
@@ -204,7 +204,7 @@
 }
 
 bool isValid(const ProgramIdentifier& id) {
-    int64_t val = id.value;
+    uint64_t val = static_cast<uint64_t>(id.value);
     bool valid = true;
 
     auto expect = [&valid](bool condition, const string& message) {
@@ -231,11 +231,11 @@
             expect(val <= 0xFFFFu, "16bit id");
             break;
         case IdentifierType::HD_STATION_ID_EXT: {
-            int64_t stationId = val & 0xFFFFFFFF;  // 32bit
+            uint64_t stationId = val & 0xFFFFFFFF;  // 32bit
             val >>= 32;
-            int64_t subchannel = val & 0xF;  // 4bit
+            uint64_t subchannel = val & 0xF;  // 4bit
             val >>= 4;
-            int64_t freq = val & 0x3FFFF;  // 18bit
+            uint64_t freq = val & 0x3FFFF;  // 18bit
             expect(stationId != 0u, "HD station id != 0");
             expect(subchannel < 8u, "HD subch < 8");
             expect(freq > 100u, "f > 100kHz");
@@ -252,9 +252,9 @@
             break;
         }
         case IdentifierType::DAB_SID_EXT: {
-            int64_t sid = val & 0xFFFFFFFF;  // 32bit
+            uint64_t sid = val & 0xFFFFFFFF;  // 32bit
             val >>= 32;
-            int64_t ecc = val & 0xFF;  // 8bit
+            uint64_t ecc = val & 0xFF;  // 8bit
             expect(sid != 0u, "DAB SId != 0");
             expect(ecc >= 0xA0u && ecc <= 0xF6u, "Invalid ECC, see ETSI TS 101 756 V2.1.1");
             break;
@@ -305,19 +305,19 @@
     return {type, value};
 }
 
-ProgramSelector makeSelectorAmfm(int32_t frequency) {
+ProgramSelector makeSelectorAmfm(uint32_t frequency) {
     ProgramSelector sel = {};
     sel.primaryId = makeIdentifier(IdentifierType::AMFM_FREQUENCY_KHZ, frequency);
     return sel;
 }
 
-ProgramSelector makeSelectorDab(int64_t sidExt) {
+ProgramSelector makeSelectorDab(uint64_t sidExt) {
     ProgramSelector sel = {};
     sel.primaryId = makeIdentifier(IdentifierType::DAB_SID_EXT, sidExt);
     return sel;
 }
 
-ProgramSelector makeSelectorDab(int64_t sidExt, int32_t ensemble, int64_t freq) {
+ProgramSelector makeSelectorDab(uint64_t sidExt, uint32_t ensemble, uint64_t freq) {
     ProgramSelector sel = {};
     sel.primaryId = makeIdentifier(IdentifierType::DAB_SID_EXT, sidExt);
     vector<ProgramIdentifier> secondaryIds = {
diff --git a/broadcastradio/common/utilsaidl/include/broadcastradio-utils-aidl/Utils.h b/broadcastradio/common/utilsaidl/include/broadcastradio-utils-aidl/Utils.h
index ad075f2..ee85a17 100644
--- a/broadcastradio/common/utilsaidl/include/broadcastradio-utils-aidl/Utils.h
+++ b/broadcastradio/common/utilsaidl/include/broadcastradio-utils-aidl/Utils.h
@@ -137,9 +137,9 @@
 bool isValid(const ProgramSelector& sel);
 
 ProgramIdentifier makeIdentifier(IdentifierType type, int64_t value);
-ProgramSelector makeSelectorAmfm(int32_t frequency);
-ProgramSelector makeSelectorDab(int64_t sidExt);
-ProgramSelector makeSelectorDab(int64_t sidExt, int32_t ensemble, int64_t freq);
+ProgramSelector makeSelectorAmfm(uint32_t frequency);
+ProgramSelector makeSelectorDab(uint64_t sidExt);
+ProgramSelector makeSelectorDab(uint64_t sidExt, uint32_t ensemble, uint64_t freq);
 
 bool satisfies(const ProgramFilter& filter, const ProgramSelector& sel);
 
diff --git a/camera/common/default/Android.bp b/camera/common/default/Android.bp
index e8c8f9d..b5d3095 100644
--- a/camera/common/default/Android.bp
+++ b/camera/common/default/Android.bp
@@ -30,13 +30,12 @@
         "libgralloctypes",
         "libhardware",
         "libcamera_metadata",
-        "android.hardware.graphics.mapper@2.0",
-        "android.hardware.graphics.mapper@3.0",
-        "android.hardware.graphics.mapper@4.0",
         "libexif",
+        "libui",
     ],
     include_dirs: ["system/media/private/camera/include"],
     export_include_dirs: ["include"],
+    export_shared_lib_headers: ["libui"],
 }
 
 // NOTE: Deprecated module kept for compatibility reasons.
diff --git a/camera/common/default/HandleImporter.cpp b/camera/common/default/HandleImporter.cpp
index 1145baa..9c579e5 100644
--- a/camera/common/default/HandleImporter.cpp
+++ b/camera/common/default/HandleImporter.cpp
@@ -17,9 +17,10 @@
 #define LOG_TAG "HandleImporter"
 #include "HandleImporter.h"
 
+#include <aidl/android/hardware/graphics/common/Smpte2086.h>
 #include <gralloctypes/Gralloc4.h>
 #include <log/log.h>
-#include "aidl/android/hardware/graphics/common/Smpte2086.h"
+#include <ui/GraphicBufferMapper.h>
 
 namespace android {
 namespace hardware {
@@ -31,12 +32,6 @@
 using aidl::android::hardware::graphics::common::PlaneLayoutComponent;
 using aidl::android::hardware::graphics::common::PlaneLayoutComponentType;
 using aidl::android::hardware::graphics::common::Smpte2086;
-using MetadataType = android::hardware::graphics::mapper::V4_0::IMapper::MetadataType;
-using MapperErrorV2 = android::hardware::graphics::mapper::V2_0::Error;
-using MapperErrorV3 = android::hardware::graphics::mapper::V3_0::Error;
-using MapperErrorV4 = android::hardware::graphics::mapper::V4_0::Error;
-using IMapperV3 = android::hardware::graphics::mapper::V3_0::IMapper;
-using IMapperV4 = android::hardware::graphics::mapper::V4_0::IMapper;
 
 HandleImporter::HandleImporter() : mInitialized(false) {}
 
@@ -45,51 +40,20 @@
         return;
     }
 
-    mMapperV4 = IMapperV4::getService();
-    if (mMapperV4 != nullptr) {
-        mInitialized = true;
-        return;
-    }
-
-    mMapperV3 = IMapperV3::getService();
-    if (mMapperV3 != nullptr) {
-        mInitialized = true;
-        return;
-    }
-
-    mMapperV2 = IMapper::getService();
-    if (mMapperV2 == nullptr) {
-        ALOGE("%s: cannnot acccess graphics mapper HAL!", __FUNCTION__);
-        return;
-    }
-
+    GraphicBufferMapper::preloadHal();
     mInitialized = true;
     return;
 }
 
 void HandleImporter::cleanup() {
-    mMapperV4.clear();
-    mMapperV3.clear();
-    mMapperV2.clear();
     mInitialized = false;
 }
 
-template <class M, class E>
-bool HandleImporter::importBufferInternal(const sp<M> mapper, buffer_handle_t& handle) {
-    E error;
+bool HandleImporter::importBufferInternal(buffer_handle_t& handle) {
     buffer_handle_t importedHandle;
-    auto ret = mapper->importBuffer(
-            hidl_handle(handle), [&](const auto& tmpError, const auto& tmpBufferHandle) {
-                error = tmpError;
-                importedHandle = static_cast<buffer_handle_t>(tmpBufferHandle);
-            });
-
-    if (!ret.isOk()) {
-        ALOGE("%s: mapper importBuffer failed: %s", __FUNCTION__, ret.description().c_str());
-        return false;
-    }
-
-    if (error != E::NONE) {
+    auto status = GraphicBufferMapper::get().importBufferNoValidate(handle, &importedHandle);
+    if (status != OK) {
+        ALOGE("%s: mapper importBuffer failed: %d", __FUNCTION__, status);
         return false;
     }
 
@@ -97,172 +61,34 @@
     return true;
 }
 
-template <class M, class E>
-YCbCrLayout HandleImporter::lockYCbCrInternal(const sp<M> mapper, buffer_handle_t& buf,
-                                              uint64_t cpuUsage,
-                                              const IMapper::Rect& accessRegion) {
-    hidl_handle acquireFenceHandle;
-    auto buffer = const_cast<native_handle_t*>(buf);
-    YCbCrLayout layout = {};
+android_ycbcr HandleImporter::lockYCbCr(buffer_handle_t& buf, uint64_t cpuUsage,
+                                        const android::Rect& accessRegion) {
+    Mutex::Autolock lock(mLock);
 
-    typename M::Rect accessRegionCopy = {accessRegion.left, accessRegion.top, accessRegion.width,
-                                         accessRegion.height};
-    mapper->lockYCbCr(buffer, cpuUsage, accessRegionCopy, acquireFenceHandle,
-                      [&](const auto& tmpError, const auto& tmpLayout) {
-                          if (tmpError == E::NONE) {
-                              // Member by member copy from different versions of YCbCrLayout.
-                              layout.y = tmpLayout.y;
-                              layout.cb = tmpLayout.cb;
-                              layout.cr = tmpLayout.cr;
-                              layout.yStride = tmpLayout.yStride;
-                              layout.cStride = tmpLayout.cStride;
-                              layout.chromaStep = tmpLayout.chromaStep;
-                          } else {
-                              ALOGE("%s: failed to lockYCbCr error %d!", __FUNCTION__, tmpError);
-                          }
-                      });
+    if (!mInitialized) {
+        initializeLocked();
+    }
+    android_ycbcr layout;
+
+    status_t status = GraphicBufferMapper::get().lockYCbCr(buf, cpuUsage, accessRegion, &layout);
+
+    if (status != OK) {
+        ALOGE("%s: failed to lockYCbCr error %d!", __FUNCTION__, status);
+    }
+
     return layout;
 }
 
-bool isMetadataPesent(const sp<IMapperV4> mapper, const buffer_handle_t& buf,
-                      MetadataType metadataType) {
-    auto buffer = const_cast<native_handle_t*>(buf);
-    bool ret = false;
-    hidl_vec<uint8_t> vec;
-    mapper->get(buffer, metadataType, [&](const auto& tmpError, const auto& tmpMetadata) {
-        if (tmpError == MapperErrorV4::NONE) {
-            vec = tmpMetadata;
-        } else {
-            ALOGE("%s: failed to get metadata %d!", __FUNCTION__, tmpError);
-        }
-    });
-
-    if (vec.size() > 0) {
-        if (metadataType == gralloc4::MetadataType_Smpte2086) {
-            std::optional<Smpte2086> realSmpte2086;
-            gralloc4::decodeSmpte2086(vec, &realSmpte2086);
-            ret = realSmpte2086.has_value();
-        } else if (metadataType == gralloc4::MetadataType_Smpte2094_10) {
-            std::optional<std::vector<uint8_t>> realSmpte2094_10;
-            gralloc4::decodeSmpte2094_10(vec, &realSmpte2094_10);
-            ret = realSmpte2094_10.has_value();
-        } else if (metadataType == gralloc4::MetadataType_Smpte2094_40) {
-            std::optional<std::vector<uint8_t>> realSmpte2094_40;
-            gralloc4::decodeSmpte2094_40(vec, &realSmpte2094_40);
-            ret = realSmpte2094_40.has_value();
-        } else {
-            ALOGE("%s: Unknown metadata type!", __FUNCTION__);
-        }
-    }
-
-    return ret;
-}
-
-std::vector<PlaneLayout> getPlaneLayouts(const sp<IMapperV4> mapper, buffer_handle_t& buf) {
-    auto buffer = const_cast<native_handle_t*>(buf);
+std::vector<PlaneLayout> getPlaneLayouts(buffer_handle_t& buf) {
     std::vector<PlaneLayout> planeLayouts;
-    hidl_vec<uint8_t> encodedPlaneLayouts;
-    mapper->get(buffer, gralloc4::MetadataType_PlaneLayouts,
-                [&](const auto& tmpError, const auto& tmpEncodedPlaneLayouts) {
-                    if (tmpError == MapperErrorV4::NONE) {
-                        encodedPlaneLayouts = tmpEncodedPlaneLayouts;
-                    } else {
-                        ALOGE("%s: failed to get plane layouts %d!", __FUNCTION__, tmpError);
-                    }
-                });
-
-    gralloc4::decodePlaneLayouts(encodedPlaneLayouts, &planeLayouts);
+    status_t status = GraphicBufferMapper::get().getPlaneLayouts(buf, &planeLayouts);
+    if (status != OK) {
+        ALOGE("%s: failed to get PlaneLayouts! Status %d", __FUNCTION__, status);
+    }
 
     return planeLayouts;
 }
 
-template <>
-YCbCrLayout HandleImporter::lockYCbCrInternal<IMapperV4, MapperErrorV4>(
-        const sp<IMapperV4> mapper, buffer_handle_t& buf, uint64_t cpuUsage,
-        const IMapper::Rect& accessRegion) {
-    hidl_handle acquireFenceHandle;
-    auto buffer = const_cast<native_handle_t*>(buf);
-    YCbCrLayout layout = {};
-    void* mapped = nullptr;
-
-    typename IMapperV4::Rect accessRegionV4 = {accessRegion.left, accessRegion.top,
-                                               accessRegion.width, accessRegion.height};
-    mapper->lock(buffer, cpuUsage, accessRegionV4, acquireFenceHandle,
-                 [&](const auto& tmpError, const auto& tmpPtr) {
-                     if (tmpError == MapperErrorV4::NONE) {
-                         mapped = tmpPtr;
-                     } else {
-                         ALOGE("%s: failed to lock error %d!", __FUNCTION__, tmpError);
-                     }
-                 });
-
-    if (mapped == nullptr) {
-        return layout;
-    }
-
-    std::vector<PlaneLayout> planeLayouts = getPlaneLayouts(mapper, buf);
-    for (const auto& planeLayout : planeLayouts) {
-        for (const auto& planeLayoutComponent : planeLayout.components) {
-            const auto& type = planeLayoutComponent.type;
-
-            if (!gralloc4::isStandardPlaneLayoutComponentType(type)) {
-                continue;
-            }
-
-            uint8_t* data = reinterpret_cast<uint8_t*>(mapped);
-            data += planeLayout.offsetInBytes;
-            data += planeLayoutComponent.offsetInBits / 8;
-
-            switch (static_cast<PlaneLayoutComponentType>(type.value)) {
-                case PlaneLayoutComponentType::Y:
-                    layout.y = data;
-                    layout.yStride = planeLayout.strideInBytes;
-                    break;
-                case PlaneLayoutComponentType::CB:
-                    layout.cb = data;
-                    layout.cStride = planeLayout.strideInBytes;
-                    layout.chromaStep = planeLayout.sampleIncrementInBits / 8;
-                    break;
-                case PlaneLayoutComponentType::CR:
-                    layout.cr = data;
-                    layout.cStride = planeLayout.strideInBytes;
-                    layout.chromaStep = planeLayout.sampleIncrementInBits / 8;
-                    break;
-                default:
-                    break;
-            }
-        }
-    }
-
-    return layout;
-}
-
-template <class M, class E>
-int HandleImporter::unlockInternal(const sp<M> mapper, buffer_handle_t& buf) {
-    int releaseFence = -1;
-    auto buffer = const_cast<native_handle_t*>(buf);
-
-    mapper->unlock(buffer, [&](const auto& tmpError, const auto& tmpReleaseFence) {
-        if (tmpError == E::NONE) {
-            auto fenceHandle = tmpReleaseFence.getNativeHandle();
-            if (fenceHandle) {
-                if (fenceHandle->numInts != 0 || fenceHandle->numFds != 1) {
-                    ALOGE("%s: bad release fence numInts %d numFds %d", __FUNCTION__,
-                          fenceHandle->numInts, fenceHandle->numFds);
-                    return;
-                }
-                releaseFence = dup(fenceHandle->data[0]);
-                if (releaseFence < 0) {
-                    ALOGE("%s: bad release fence FD %d", __FUNCTION__, releaseFence);
-                }
-            }
-        } else {
-            ALOGE("%s: failed to unlock error %d!", __FUNCTION__, tmpError);
-        }
-    });
-    return releaseFence;
-}
-
 // In IComposer, any buffer_handle_t is owned by the caller and we need to
 // make a clone for hwcomposer2.  We also need to translate empty handle
 // to nullptr.  This function does that, in-place.
@@ -277,20 +103,7 @@
         initializeLocked();
     }
 
-    if (mMapperV4 != nullptr) {
-        return importBufferInternal<IMapperV4, MapperErrorV4>(mMapperV4, handle);
-    }
-
-    if (mMapperV3 != nullptr) {
-        return importBufferInternal<IMapperV3, MapperErrorV3>(mMapperV3, handle);
-    }
-
-    if (mMapperV2 != nullptr) {
-        return importBufferInternal<IMapper, MapperErrorV2>(mMapperV2, handle);
-    }
-
-    ALOGE("%s: mMapperV4, mMapperV3 and mMapperV2 are all null!", __FUNCTION__);
-    return false;
+    return importBufferInternal(handle);
 }
 
 void HandleImporter::freeBuffer(buffer_handle_t handle) {
@@ -303,21 +116,9 @@
         initializeLocked();
     }
 
-    if (mMapperV4 != nullptr) {
-        auto ret = mMapperV4->freeBuffer(const_cast<native_handle_t*>(handle));
-        if (!ret.isOk()) {
-            ALOGE("%s: mapper freeBuffer failed: %s", __FUNCTION__, ret.description().c_str());
-        }
-    } else if (mMapperV3 != nullptr) {
-        auto ret = mMapperV3->freeBuffer(const_cast<native_handle_t*>(handle));
-        if (!ret.isOk()) {
-            ALOGE("%s: mapper freeBuffer failed: %s", __FUNCTION__, ret.description().c_str());
-        }
-    } else {
-        auto ret = mMapperV2->freeBuffer(const_cast<native_handle_t*>(handle));
-        if (!ret.isOk()) {
-            ALOGE("%s: mapper freeBuffer failed: %s", __FUNCTION__, ret.description().c_str());
-        }
+    status_t status = GraphicBufferMapper::get().freeBuffer(handle);
+    if (status != OK) {
+        ALOGE("%s: mapper freeBuffer failed. Status %d", __FUNCTION__, status);
     }
 }
 
@@ -345,12 +146,12 @@
 }
 
 void* HandleImporter::lock(buffer_handle_t& buf, uint64_t cpuUsage, size_t size) {
-    IMapper::Rect accessRegion{0, 0, static_cast<int>(size), 1};
+    android::Rect accessRegion{0, 0, static_cast<int>(size), 1};
     return lock(buf, cpuUsage, accessRegion);
 }
 
 void* HandleImporter::lock(buffer_handle_t& buf, uint64_t cpuUsage,
-                           const IMapper::Rect& accessRegion) {
+                           const android::Rect& accessRegion) {
     Mutex::Autolock lock(mLock);
 
     if (!mInitialized) {
@@ -358,81 +159,18 @@
     }
 
     void* ret = nullptr;
-
-    if (mMapperV4 == nullptr && mMapperV3 == nullptr && mMapperV2 == nullptr) {
-        ALOGE("%s: mMapperV4, mMapperV3 and mMapperV2 are all null!", __FUNCTION__);
-        return ret;
-    }
-
-    hidl_handle acquireFenceHandle;
-    auto buffer = const_cast<native_handle_t*>(buf);
-    if (mMapperV4 != nullptr) {
-        IMapperV4::Rect accessRegionV4{accessRegion.left, accessRegion.top, accessRegion.width,
-                                       accessRegion.height};
-
-        mMapperV4->lock(buffer, cpuUsage, accessRegionV4, acquireFenceHandle,
-                        [&](const auto& tmpError, const auto& tmpPtr) {
-                            if (tmpError == MapperErrorV4::NONE) {
-                                ret = tmpPtr;
-                            } else {
-                                ALOGE("%s: failed to lock error %d!", __FUNCTION__, tmpError);
-                            }
-                        });
-    } else if (mMapperV3 != nullptr) {
-        IMapperV3::Rect accessRegionV3{accessRegion.left, accessRegion.top, accessRegion.width,
-                                       accessRegion.height};
-
-        mMapperV3->lock(buffer, cpuUsage, accessRegionV3, acquireFenceHandle,
-                        [&](const auto& tmpError, const auto& tmpPtr, const auto& /*bytesPerPixel*/,
-                            const auto& /*bytesPerStride*/) {
-                            if (tmpError == MapperErrorV3::NONE) {
-                                ret = tmpPtr;
-                            } else {
-                                ALOGE("%s: failed to lock error %d!", __FUNCTION__, tmpError);
-                            }
-                        });
-    } else {
-        mMapperV2->lock(buffer, cpuUsage, accessRegion, acquireFenceHandle,
-                        [&](const auto& tmpError, const auto& tmpPtr) {
-                            if (tmpError == MapperErrorV2::NONE) {
-                                ret = tmpPtr;
-                            } else {
-                                ALOGE("%s: failed to lock error %d!", __FUNCTION__, tmpError);
-                            }
-                        });
+    status_t status = GraphicBufferMapper::get().lock(buf, cpuUsage, accessRegion, &ret);
+    if (status != OK) {
+        ALOGE("%s: failed to lock error %d!", __FUNCTION__, status);
     }
 
     ALOGV("%s: ptr %p accessRegion.top: %d accessRegion.left: %d accessRegion.width: %d "
           "accessRegion.height: %d",
-          __FUNCTION__, ret, accessRegion.top, accessRegion.left, accessRegion.width,
-          accessRegion.height);
+          __FUNCTION__, ret, accessRegion.top, accessRegion.left, accessRegion.width(),
+          accessRegion.height());
     return ret;
 }
 
-YCbCrLayout HandleImporter::lockYCbCr(buffer_handle_t& buf, uint64_t cpuUsage,
-                                      const IMapper::Rect& accessRegion) {
-    Mutex::Autolock lock(mLock);
-
-    if (!mInitialized) {
-        initializeLocked();
-    }
-
-    if (mMapperV4 != nullptr) {
-        return lockYCbCrInternal<IMapperV4, MapperErrorV4>(mMapperV4, buf, cpuUsage, accessRegion);
-    }
-
-    if (mMapperV3 != nullptr) {
-        return lockYCbCrInternal<IMapperV3, MapperErrorV3>(mMapperV3, buf, cpuUsage, accessRegion);
-    }
-
-    if (mMapperV2 != nullptr) {
-        return lockYCbCrInternal<IMapper, MapperErrorV2>(mMapperV2, buf, cpuUsage, accessRegion);
-    }
-
-    ALOGE("%s: mMapperV4, mMapperV3 and mMapperV2 are all null!", __FUNCTION__);
-    return {};
-}
-
 status_t HandleImporter::getMonoPlanarStrideBytes(buffer_handle_t& buf, uint32_t* stride /*out*/) {
     if (stride == nullptr) {
         return BAD_VALUE;
@@ -444,35 +182,26 @@
         initializeLocked();
     }
 
-    if (mMapperV4 != nullptr) {
-        std::vector<PlaneLayout> planeLayouts = getPlaneLayouts(mMapperV4, buf);
-        if (planeLayouts.size() != 1) {
-            ALOGE("%s: Unexpected number of planes %zu!", __FUNCTION__, planeLayouts.size());
-            return BAD_VALUE;
-        }
-
-        *stride = planeLayouts[0].strideInBytes;
-    } else {
-        ALOGE("%s: mMapperV4 is null! Query not supported!", __FUNCTION__);
-        return NO_INIT;
+    std::vector<PlaneLayout> planeLayouts = getPlaneLayouts(buf);
+    if (planeLayouts.size() != 1) {
+        ALOGE("%s: Unexpected number of planes %zu!", __FUNCTION__, planeLayouts.size());
+        return BAD_VALUE;
     }
 
+    *stride = planeLayouts[0].strideInBytes;
+
     return OK;
 }
 
 int HandleImporter::unlock(buffer_handle_t& buf) {
-    if (mMapperV4 != nullptr) {
-        return unlockInternal<IMapperV4, MapperErrorV4>(mMapperV4, buf);
-    }
-    if (mMapperV3 != nullptr) {
-        return unlockInternal<IMapperV3, MapperErrorV3>(mMapperV3, buf);
-    }
-    if (mMapperV2 != nullptr) {
-        return unlockInternal<IMapper, MapperErrorV2>(mMapperV2, buf);
+    int releaseFence = -1;
+
+    status_t status = GraphicBufferMapper::get().unlockAsync(buf, &releaseFence);
+    if (status != OK) {
+        ALOGE("%s: failed to unlock error %d!", __FUNCTION__, status);
     }
 
-    ALOGE("%s: mMapperV4, mMapperV3 and mMapperV2 are all null!", __FUNCTION__);
-    return -1;
+    return releaseFence;
 }
 
 bool HandleImporter::isSmpte2086Present(const buffer_handle_t& buf) {
@@ -481,14 +210,14 @@
     if (!mInitialized) {
         initializeLocked();
     }
-
-    if (mMapperV4 != nullptr) {
-        return isMetadataPesent(mMapperV4, buf, gralloc4::MetadataType_Smpte2086);
-    } else {
-        ALOGE("%s: mMapperV4 is null! Query not supported!", __FUNCTION__);
+    std::optional<ui::Smpte2086> metadata;
+    status_t status = GraphicBufferMapper::get().getSmpte2086(buf, &metadata);
+    if (status != OK) {
+        ALOGE("%s: Mapper failed to get Smpte2094_40 metadata! Status: %d", __FUNCTION__, status);
+        return false;
     }
 
-    return false;
+    return metadata.has_value();
 }
 
 bool HandleImporter::isSmpte2094_10Present(const buffer_handle_t& buf) {
@@ -498,13 +227,14 @@
         initializeLocked();
     }
 
-    if (mMapperV4 != nullptr) {
-        return isMetadataPesent(mMapperV4, buf, gralloc4::MetadataType_Smpte2094_10);
-    } else {
-        ALOGE("%s: mMapperV4 is null! Query not supported!", __FUNCTION__);
+    std::optional<std::vector<uint8_t>> metadata;
+    status_t status = GraphicBufferMapper::get().getSmpte2094_10(buf, &metadata);
+    if (status != OK) {
+        ALOGE("%s: Mapper failed to get Smpte2094_40 metadata! Status: %d", __FUNCTION__, status);
+        return false;
     }
 
-    return false;
+    return metadata.has_value();
 }
 
 bool HandleImporter::isSmpte2094_40Present(const buffer_handle_t& buf) {
@@ -514,13 +244,14 @@
         initializeLocked();
     }
 
-    if (mMapperV4 != nullptr) {
-        return isMetadataPesent(mMapperV4, buf, gralloc4::MetadataType_Smpte2094_40);
-    } else {
-        ALOGE("%s: mMapperV4 is null! Query not supported!", __FUNCTION__);
+    std::optional<std::vector<uint8_t>> metadata;
+    status_t status = GraphicBufferMapper::get().getSmpte2094_40(buf, &metadata);
+    if (status != OK) {
+        ALOGE("%s: Mapper failed to get Smpte2094_40 metadata! Status: %d", __FUNCTION__, status);
+        return false;
     }
 
-    return false;
+    return metadata.has_value();
 }
 
 }  // namespace helper
diff --git a/camera/common/default/include/HandleImporter.h b/camera/common/default/include/HandleImporter.h
index 5408ba9..df01202 100644
--- a/camera/common/default/include/HandleImporter.h
+++ b/camera/common/default/include/HandleImporter.h
@@ -17,15 +17,11 @@
 #ifndef CAMERA_COMMON_1_0_HANDLEIMPORTED_H
 #define CAMERA_COMMON_1_0_HANDLEIMPORTED_H
 
-#include <android/hardware/graphics/mapper/2.0/IMapper.h>
-#include <android/hardware/graphics/mapper/3.0/IMapper.h>
-#include <android/hardware/graphics/mapper/4.0/IMapper.h>
 #include <cutils/native_handle.h>
+#include <system/graphics.h>
+#include <ui/Rect.h>
 #include <utils/Mutex.h>
 
-using android::hardware::graphics::mapper::V2_0::IMapper;
-using android::hardware::graphics::mapper::V2_0::YCbCrLayout;
-
 namespace android {
 namespace hardware {
 namespace camera {
@@ -49,11 +45,11 @@
     void* lock(buffer_handle_t& buf, uint64_t cpuUsage, size_t size);
 
     // Locks 2-D buffer. Assumes caller has waited for acquire fences.
-    void* lock(buffer_handle_t& buf, uint64_t cpuUsage, const IMapper::Rect& accessRegion);
+    void* lock(buffer_handle_t& buf, uint64_t cpuUsage, const android::Rect& accessRegion);
 
     // Assumes caller has waited for acquire fences.
-    YCbCrLayout lockYCbCr(buffer_handle_t& buf, uint64_t cpuUsage,
-                          const IMapper::Rect& accessRegion);
+    android_ycbcr lockYCbCr(buffer_handle_t& buf, uint64_t cpuUsage,
+                            const android::Rect& accessRegion);
 
     // Query the stride of the first plane in bytes.
     status_t getMonoPlanarStrideBytes(buffer_handle_t& buf, uint32_t* stride /*out*/);
@@ -69,19 +65,11 @@
     void initializeLocked();
     void cleanup();
 
-    template <class M, class E>
-    bool importBufferInternal(const sp<M> mapper, buffer_handle_t& handle);
-    template <class M, class E>
-    YCbCrLayout lockYCbCrInternal(const sp<M> mapper, buffer_handle_t& buf, uint64_t cpuUsage,
-                                  const IMapper::Rect& accessRegion);
-    template <class M, class E>
-    int unlockInternal(const sp<M> mapper, buffer_handle_t& buf);
+    bool importBufferInternal(buffer_handle_t& handle);
+    int unlockInternal(buffer_handle_t& buf);
 
     Mutex mLock;
     bool mInitialized;
-    sp<IMapper> mMapperV2;
-    sp<graphics::mapper::V3_0::IMapper> mMapperV3;
-    sp<graphics::mapper::V4_0::IMapper> mMapperV4;
 };
 
 }  // namespace helper
diff --git a/camera/device/1.0/default/Android.bp b/camera/device/1.0/default/Android.bp
index 9ff6480..6992ff0 100644
--- a/camera/device/1.0/default/Android.bp
+++ b/camera/device/1.0/default/Android.bp
@@ -32,6 +32,7 @@
         "libgralloctypes",
         "libhardware",
         "libcamera_metadata",
+        "libui",
     ],
     static_libs: [
         "android.hardware.camera.common@1.0-helper",
diff --git a/camera/device/3.2/default/Android.bp b/camera/device/3.2/default/Android.bp
index a196291..adf834a 100644
--- a/camera/device/3.2/default/Android.bp
+++ b/camera/device/3.2/default/Android.bp
@@ -30,6 +30,7 @@
         "libhardware",
         "libcamera_metadata",
         "libfmq",
+        "libui",
     ],
     static_libs: [
         "android.hardware.camera.common@1.0-helper",
diff --git a/camera/device/3.4/default/Android.bp b/camera/device/3.4/default/Android.bp
index 9f0c777..100106e 100644
--- a/camera/device/3.4/default/Android.bp
+++ b/camera/device/3.4/default/Android.bp
@@ -106,6 +106,7 @@
         "libjpeg",
         "libexif",
         "libtinyxml2",
+        "libui",
     ],
     static_libs: [
         "android.hardware.camera.common@1.0-helper",
diff --git a/camera/device/3.4/default/ExternalCameraDeviceSession.cpp b/camera/device/3.4/default/ExternalCameraDeviceSession.cpp
index ca7186b..01b3d41 100644
--- a/camera/device/3.4/default/ExternalCameraDeviceSession.cpp
+++ b/camera/device/3.4/default/ExternalCameraDeviceSession.cpp
@@ -1574,14 +1574,23 @@
             } break;
             case PixelFormat::YCBCR_420_888:
             case PixelFormat::YV12: {
-                IMapper::Rect outRect {0, 0,
-                        static_cast<int32_t>(halBuf.width),
-                        static_cast<int32_t>(halBuf.height)};
-                YCbCrLayout outLayout = sHandleImporter.lockYCbCr(
-                        *(halBuf.bufPtr), halBuf.usage, outRect);
-                ALOGV("%s: outLayout y %p cb %p cr %p y_str %d c_str %d c_step %d",
-                        __FUNCTION__, outLayout.y, outLayout.cb, outLayout.cr,
-                        outLayout.yStride, outLayout.cStride, outLayout.chromaStep);
+                android::Rect outRect{0, 0, static_cast<int32_t>(halBuf.width),
+                                      static_cast<int32_t>(halBuf.height)};
+                android_ycbcr result =
+                        sHandleImporter.lockYCbCr(*(halBuf.bufPtr), halBuf.usage, outRect);
+                ALOGV("%s: outLayout y %p cb %p cr %p y_str %zu c_str %zu c_step %zu", __FUNCTION__,
+                      result.y, result.cb, result.cr, result.ystride, result.cstride,
+                      result.chroma_step);
+                if (result.ystride > UINT32_MAX || result.cstride > UINT32_MAX ||
+                    result.chroma_step > UINT32_MAX) {
+                    return onDeviceError("%s: lockYCbCr failed. Unexpected values!", __FUNCTION__);
+                }
+                YCbCrLayout outLayout = {.y = result.y,
+                                         .cb = result.cb,
+                                         .cr = result.cr,
+                                         .yStride = static_cast<uint32_t>(result.ystride),
+                                         .cStride = static_cast<uint32_t>(result.cstride),
+                                         .chromaStep = static_cast<uint32_t>(result.chroma_step)};
 
                 // Convert to output buffer size/format
                 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
diff --git a/camera/device/3.5/default/Android.bp b/camera/device/3.5/default/Android.bp
index 9d27b32..bc15629 100644
--- a/camera/device/3.5/default/Android.bp
+++ b/camera/device/3.5/default/Android.bp
@@ -46,6 +46,7 @@
     ],
     shared_libs: [
         "libhidlbase",
+        "libui",
         "libutils",
         "libcutils",
         "camera.device@3.2-impl",
@@ -81,6 +82,7 @@
     ],
     shared_libs: [
         "libhidlbase",
+        "libui",
         "libutils",
         "libcutils",
         "camera.device@3.2-impl",
diff --git a/camera/device/3.6/default/Android.bp b/camera/device/3.6/default/Android.bp
index 89ee145..b4a486f 100644
--- a/camera/device/3.6/default/Android.bp
+++ b/camera/device/3.6/default/Android.bp
@@ -41,6 +41,7 @@
     ],
     shared_libs: [
         "libhidlbase",
+        "libui",
         "libutils",
         "libcutils",
         "camera.device@3.2-impl",
diff --git a/camera/device/3.6/default/ExternalCameraOfflineSession.cpp b/camera/device/3.6/default/ExternalCameraOfflineSession.cpp
index e606fda..1f1dfee 100644
--- a/camera/device/3.6/default/ExternalCameraOfflineSession.cpp
+++ b/camera/device/3.6/default/ExternalCameraOfflineSession.cpp
@@ -222,14 +222,23 @@
             } break;
             case PixelFormat::YCBCR_420_888:
             case PixelFormat::YV12: {
-                IMapper::Rect outRect {0, 0,
-                        static_cast<int32_t>(halBuf.width),
-                        static_cast<int32_t>(halBuf.height)};
-                YCbCrLayout outLayout = sHandleImporter.lockYCbCr(
-                        *(halBuf.bufPtr), halBuf.usage, outRect);
-                ALOGV("%s: outLayout y %p cb %p cr %p y_str %d c_str %d c_step %d",
-                        __FUNCTION__, outLayout.y, outLayout.cb, outLayout.cr,
-                        outLayout.yStride, outLayout.cStride, outLayout.chromaStep);
+                android::Rect outRect{0, 0, static_cast<int32_t>(halBuf.width),
+                                      static_cast<int32_t>(halBuf.height)};
+                android_ycbcr result =
+                        sHandleImporter.lockYCbCr(*(halBuf.bufPtr), halBuf.usage, outRect);
+                ALOGV("%s: outLayout y %p cb %p cr %p y_str %zu c_str %zu c_step %zu", __FUNCTION__,
+                      result.y, result.cb, result.cr, result.ystride, result.cstride,
+                      result.chroma_step);
+                if (result.ystride > UINT32_MAX || result.cstride > UINT32_MAX ||
+                    result.chroma_step > UINT32_MAX) {
+                    return onDeviceError("%s: lockYCbCr failed. Unexpected values!", __FUNCTION__);
+                }
+                YCbCrLayout outLayout = {.y = result.y,
+                                         .cb = result.cb,
+                                         .cr = result.cr,
+                                         .yStride = static_cast<uint32_t>(result.ystride),
+                                         .cStride = static_cast<uint32_t>(result.cstride),
+                                         .chromaStep = static_cast<uint32_t>(result.chroma_step)};
 
                 // Convert to output buffer size/format
                 uint32_t outputFourcc = V3_4::implementation::getFourCcFromLayout(outLayout);
diff --git a/camera/device/aidl/Android.bp b/camera/device/aidl/Android.bp
index 43a3934..1a665fb 100644
--- a/camera/device/aidl/Android.bp
+++ b/camera/device/aidl/Android.bp
@@ -18,7 +18,7 @@
         "android.hardware.common.fmq-V1",
         "android.hardware.camera.common-V1",
         "android.hardware.camera.metadata-V2",
-        "android.hardware.graphics.common-V4",
+        "android.hardware.graphics.common-V5",
     ],
     backend: {
         cpp: {
@@ -37,7 +37,7 @@
                 "android.hardware.common.fmq-V1",
                 "android.hardware.camera.common-V1",
                 "android.hardware.camera.metadata-V1",
-                "android.hardware.graphics.common-V4",
+                "android.hardware.graphics.common-V5",
             ],
         },
         {
@@ -47,7 +47,7 @@
                 "android.hardware.common.fmq-V1",
                 "android.hardware.camera.common-V1",
                 "android.hardware.camera.metadata-V2",
-                "android.hardware.graphics.common-V4",
+                "android.hardware.graphics.common-V5",
             ],
         },
 
diff --git a/camera/device/default/Android.bp b/camera/device/default/Android.bp
index b9f10d6..5fbcb5d 100644
--- a/camera/device/default/Android.bp
+++ b/camera/device/default/Android.bp
@@ -40,7 +40,7 @@
     shared_libs: [
         "android.hardware.camera.common-V1-ndk",
         "android.hardware.camera.device-V1-ndk",
-        "android.hardware.graphics.allocator-V1-ndk",
+        "android.hardware.graphics.allocator-V2-ndk",
         "android.hardware.graphics.mapper@2.0",
         "android.hardware.graphics.mapper@3.0",
         "android.hardware.graphics.mapper@4.0",
@@ -60,6 +60,7 @@
         "libsync",
         "libtinyxml2",
         "libutils",
+        "libui",
         "libyuv",
     ],
     static_libs: [
diff --git a/camera/device/default/ExternalCameraDeviceSession.cpp b/camera/device/default/ExternalCameraDeviceSession.cpp
index 95a36f0..896e0da 100644
--- a/camera/device/default/ExternalCameraDeviceSession.cpp
+++ b/camera/device/default/ExternalCameraDeviceSession.cpp
@@ -2882,13 +2882,23 @@
             } break;
             case PixelFormat::YCBCR_420_888:
             case PixelFormat::YV12: {
-                IMapper::Rect outRect{0, 0, static_cast<int32_t>(halBuf.width),
+                android::Rect outRect{0, 0, static_cast<int32_t>(halBuf.width),
                                       static_cast<int32_t>(halBuf.height)};
-                YCbCrLayout outLayout = sHandleImporter.lockYCbCr(
+                android_ycbcr result = sHandleImporter.lockYCbCr(
                         *(halBuf.bufPtr), static_cast<uint64_t>(halBuf.usage), outRect);
-                ALOGV("%s: outLayout y %p cb %p cr %p y_str %d c_str %d c_step %d", __FUNCTION__,
-                      outLayout.y, outLayout.cb, outLayout.cr, outLayout.yStride, outLayout.cStride,
-                      outLayout.chromaStep);
+                ALOGV("%s: outLayout y %p cb %p cr %p y_str %zu c_str %zu c_step %zu", __FUNCTION__,
+                      result.y, result.cb, result.cr, result.ystride, result.cstride,
+                      result.chroma_step);
+                if (result.ystride > UINT32_MAX || result.cstride > UINT32_MAX ||
+                    result.chroma_step > UINT32_MAX) {
+                    return onDeviceError("%s: lockYCbCr failed. Unexpected values!", __FUNCTION__);
+                }
+                YCbCrLayout outLayout = {.y = result.y,
+                                         .cb = result.cb,
+                                         .cr = result.cr,
+                                         .yStride = static_cast<uint32_t>(result.ystride),
+                                         .cStride = static_cast<uint32_t>(result.cstride),
+                                         .chromaStep = static_cast<uint32_t>(result.chroma_step)};
 
                 // Convert to output buffer size/format
                 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
diff --git a/camera/device/default/ExternalCameraDeviceSession.h b/camera/device/default/ExternalCameraDeviceSession.h
index 836266f..736bfd1 100644
--- a/camera/device/default/ExternalCameraDeviceSession.h
+++ b/camera/device/default/ExternalCameraDeviceSession.h
@@ -24,6 +24,9 @@
 #include <aidl/android/hardware/camera/device/BufferRequest.h>
 #include <aidl/android/hardware/camera/device/Stream.h>
 #include <android-base/unique_fd.h>
+#include <android/hardware/graphics/mapper/2.0/IMapper.h>
+#include <android/hardware/graphics/mapper/3.0/IMapper.h>
+#include <android/hardware/graphics/mapper/4.0/IMapper.h>
 #include <fmq/AidlMessageQueue.h>
 #include <utils/Thread.h>
 #include <deque>
@@ -55,6 +58,7 @@
 using ::android::hardware::camera::common::helper::SimpleThread;
 using ::android::hardware::camera::external::common::ExternalCameraConfig;
 using ::android::hardware::camera::external::common::SizeHasher;
+using ::android::hardware::graphics::mapper::V2_0::YCbCrLayout;
 using ::ndk::ScopedAStatus;
 
 class ExternalCameraDeviceSession : public BnCameraDeviceSession, public OutputThreadInterface {
diff --git a/camera/device/default/ExternalCameraOfflineSession.cpp b/camera/device/default/ExternalCameraOfflineSession.cpp
index 4c7f732..53bd44f 100644
--- a/camera/device/default/ExternalCameraOfflineSession.cpp
+++ b/camera/device/default/ExternalCameraOfflineSession.cpp
@@ -486,13 +486,23 @@
             } break;
             case PixelFormat::YCBCR_420_888:
             case PixelFormat::YV12: {
-                IMapper::Rect outRect{0, 0, static_cast<int32_t>(halBuf.width),
+                android::Rect outRect{0, 0, static_cast<int32_t>(halBuf.width),
                                       static_cast<int32_t>(halBuf.height)};
-                YCbCrLayout outLayout = sHandleImporter.lockYCbCr(
+                android_ycbcr result = sHandleImporter.lockYCbCr(
                         *(halBuf.bufPtr), static_cast<uint64_t>(halBuf.usage), outRect);
-                ALOGV("%s: outLayout y %p cb %p cr %p y_str %d c_str %d c_step %d", __FUNCTION__,
-                      outLayout.y, outLayout.cb, outLayout.cr, outLayout.yStride, outLayout.cStride,
-                      outLayout.chromaStep);
+                ALOGV("%s: outLayout y %p cb %p cr %p y_str %zu c_str %zu c_step %zu", __FUNCTION__,
+                      result.y, result.cb, result.cr, result.ystride, result.cstride,
+                      result.chroma_step);
+                if (result.ystride > UINT32_MAX || result.cstride > UINT32_MAX ||
+                    result.chroma_step > UINT32_MAX) {
+                    return onDeviceError("%s: lockYCbCr failed. Unexpected values!", __FUNCTION__);
+                }
+                YCbCrLayout outLayout = {.y = result.y,
+                                         .cb = result.cb,
+                                         .cr = result.cr,
+                                         .yStride = static_cast<uint32_t>(result.ystride),
+                                         .cStride = static_cast<uint32_t>(result.cstride),
+                                         .chromaStep = static_cast<uint32_t>(result.chroma_step)};
 
                 // Convert to output buffer size/format
                 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
@@ -544,4 +554,4 @@
 }  // namespace device
 }  // namespace camera
 }  // namespace hardware
-}  // namespace android
\ No newline at end of file
+}  // namespace android
diff --git a/camera/device/default/ExternalCameraUtils.h b/camera/device/default/ExternalCameraUtils.h
index b37933c..d434905 100644
--- a/camera/device/default/ExternalCameraUtils.h
+++ b/camera/device/default/ExternalCameraUtils.h
@@ -25,7 +25,11 @@
 #include <aidl/android/hardware/camera/device/NotifyMsg.h>
 #include <aidl/android/hardware/graphics/common/BufferUsage.h>
 #include <aidl/android/hardware/graphics/common/PixelFormat.h>
+#include <android/hardware/graphics/mapper/2.0/IMapper.h>
+#include <android/hardware/graphics/mapper/3.0/IMapper.h>
+#include <android/hardware/graphics/mapper/4.0/IMapper.h>
 #include <tinyxml2.h>
+#include <map>
 #include <unordered_map>
 #include <unordered_set>
 
@@ -37,6 +41,8 @@
 using ::aidl::android::hardware::graphics::common::PixelFormat;
 using ::android::hardware::camera::common::V1_0::helper::CameraMetadata;
 using ::android::hardware::camera::common::V1_0::helper::HandleImporter;
+using ::android::hardware::graphics::mapper::V2_0::IMapper;
+using ::android::hardware::graphics::mapper::V2_0::YCbCrLayout;
 
 namespace android {
 namespace hardware {
diff --git a/camera/metadata/aidl/Android.bp b/camera/metadata/aidl/Android.bp
index 5872a86..2b2be55 100644
--- a/camera/metadata/aidl/Android.bp
+++ b/camera/metadata/aidl/Android.bp
@@ -11,7 +11,7 @@
     name: "android.hardware.camera.metadata",
     vendor_available: true,
     srcs: ["android/hardware/camera/metadata/*.aidl"],
-    frozen: true,
+    frozen: false,
     stability: "vintf",
     backend: {
         cpp: {
diff --git a/camera/metadata/aidl/aidl_api/android.hardware.camera.metadata/current/android/hardware/camera/metadata/CameraMetadataTag.aidl b/camera/metadata/aidl/aidl_api/android.hardware.camera.metadata/current/android/hardware/camera/metadata/CameraMetadataTag.aidl
index 71d4e41..0290aef 100644
--- a/camera/metadata/aidl/aidl_api/android.hardware.camera.metadata/current/android/hardware/camera/metadata/CameraMetadataTag.aidl
+++ b/camera/metadata/aidl/aidl_api/android.hardware.camera.metadata/current/android/hardware/camera/metadata/CameraMetadataTag.aidl
@@ -108,6 +108,11 @@
   ANDROID_FLASH_COLOR_TEMPERATURE,
   ANDROID_FLASH_MAX_ENERGY,
   ANDROID_FLASH_STATE,
+  ANDROID_FLASH_STRENGTH_LEVEL,
+  ANDROID_FLASH_SINGLE_STRENGTH_MAX_LEVEL,
+  ANDROID_FLASH_SINGLE_STRENGTH_DEFAULT_LEVEL,
+  ANDROID_FLASH_TORCH_STRENGTH_MAX_LEVEL,
+  ANDROID_FLASH_TORCH_STRENGTH_DEFAULT_LEVEL,
   ANDROID_FLASH_INFO_AVAILABLE = android.hardware.camera.metadata.CameraMetadataSectionStart.ANDROID_FLASH_INFO_START /* 327680 */,
   ANDROID_FLASH_INFO_CHARGE_DURATION,
   ANDROID_FLASH_INFO_STRENGTH_MAXIMUM_LEVEL,
diff --git a/camera/metadata/aidl/android/hardware/camera/metadata/CameraMetadataTag.aidl b/camera/metadata/aidl/android/hardware/camera/metadata/CameraMetadataTag.aidl
index 56aa690..dd679f3 100644
--- a/camera/metadata/aidl/android/hardware/camera/metadata/CameraMetadataTag.aidl
+++ b/camera/metadata/aidl/android/hardware/camera/metadata/CameraMetadataTag.aidl
@@ -560,6 +560,36 @@
      */
     ANDROID_FLASH_STATE,
     /**
+     * android.flash.strengthLevel [dynamic, int32, public]
+     *
+     * <p>Flash strength level to be used when manual flash control is active.</p>
+     */
+    ANDROID_FLASH_STRENGTH_LEVEL,
+    /**
+     * android.flash.singleStrengthMaxLevel [static, int32, public]
+     *
+     * <p>Maximum flash brightness level for manual flash control in SINGLE mode.</p>
+     */
+    ANDROID_FLASH_SINGLE_STRENGTH_MAX_LEVEL,
+    /**
+     * android.flash.singleStrengthDefaultLevel [static, int32, public]
+     *
+     * <p>Default flash brightness level for manual flash control in SINGLE mode.</p>
+     */
+    ANDROID_FLASH_SINGLE_STRENGTH_DEFAULT_LEVEL,
+    /**
+     * android.flash.torchStrengthMaxLevel [static, int32, public]
+     *
+     * <p>Maximum flash brightness level for manual flash control in TORCH mode</p>
+     */
+    ANDROID_FLASH_TORCH_STRENGTH_MAX_LEVEL,
+    /**
+     * android.flash.torchStrengthDefaultLevel [static, int32, public]
+     *
+     * <p>Default flash brightness level for manual flash control in TORCH mode</p>
+     */
+    ANDROID_FLASH_TORCH_STRENGTH_DEFAULT_LEVEL,
+    /**
      * android.flash.info.available [static, enum, public]
      *
      * <p>Whether this camera device has a
diff --git a/camera/provider/2.4/default/ExternalCameraProviderImpl_2_4.cpp b/camera/provider/2.4/default/ExternalCameraProviderImpl_2_4.cpp
index 04db7f3..2d919cc 100644
--- a/camera/provider/2.4/default/ExternalCameraProviderImpl_2_4.cpp
+++ b/camera/provider/2.4/default/ExternalCameraProviderImpl_2_4.cpp
@@ -95,13 +95,14 @@
 
 Return<Status> ExternalCameraProviderImpl_2_4::setCallback(
         const sp<ICameraProviderCallback>& callback) {
+    if (callback == nullptr) {
+        return Status::ILLEGAL_ARGUMENT;
+    }
+
     {
         Mutex::Autolock _l(mLock);
         mCallbacks = callback;
     }
-    if (mCallbacks == nullptr) {
-        return Status::OK;
-    }
     // Send a callback for all devices to initialize
     {
         for (const auto& pair : mCameraStatusMap) {
diff --git a/camera/provider/2.4/default/LegacyCameraProviderImpl_2_4.cpp b/camera/provider/2.4/default/LegacyCameraProviderImpl_2_4.cpp
index 69318c7..07ed689 100644
--- a/camera/provider/2.4/default/LegacyCameraProviderImpl_2_4.cpp
+++ b/camera/provider/2.4/default/LegacyCameraProviderImpl_2_4.cpp
@@ -448,11 +448,11 @@
 // Methods from ::android::hardware::camera::provider::V2_4::ICameraProvider follow.
 Return<Status> LegacyCameraProviderImpl_2_4::setCallback(
         const sp<ICameraProviderCallback>& callback) {
+    if (callback == nullptr) {
+        return Status::ILLEGAL_ARGUMENT;
+    }
     Mutex::Autolock _l(mCbLock);
     mCallbacks = callback;
-    if (mCallbacks == nullptr) {
-        return Status::OK;
-    }
     // Add and report all presenting external cameras.
     for (auto const& statusPair : mCameraStatusMap) {
         int id = std::stoi(statusPair.first);
diff --git a/camera/provider/2.7/default/ExternalCameraProviderImpl_2_7.cpp b/camera/provider/2.7/default/ExternalCameraProviderImpl_2_7.cpp
index 62ce074..eba49a5 100644
--- a/camera/provider/2.7/default/ExternalCameraProviderImpl_2_7.cpp
+++ b/camera/provider/2.7/default/ExternalCameraProviderImpl_2_7.cpp
@@ -91,11 +91,11 @@
 
 Return<Status> ExternalCameraProviderImpl_2_7::setCallback(
         const sp<ICameraProviderCallback>& callback) {
+    if (callback == nullptr) {
+        return Status::ILLEGAL_ARGUMENT;
+    }
     Mutex::Autolock _l(mLock);
     mCallbacks = callback;
-    if (mCallbacks == nullptr) {
-        return Status::OK;
-    }
     // Send a callback for all devices to initialize
     {
         for (const auto& pair : mCameraStatusMap) {
diff --git a/camera/provider/aidl/vts/VtsAidlHalCameraProvider_TargetTest.cpp b/camera/provider/aidl/vts/VtsAidlHalCameraProvider_TargetTest.cpp
index 2845180..b6b5206 100644
--- a/camera/provider/aidl/vts/VtsAidlHalCameraProvider_TargetTest.cpp
+++ b/camera/provider/aidl/vts/VtsAidlHalCameraProvider_TargetTest.cpp
@@ -242,6 +242,7 @@
         verifyCameraCharacteristics(chars);
         verifyMonochromeCharacteristics(chars);
         verifyRecommendedConfigs(chars);
+        verifyHighSpeedRecordingCharacteristics(name, chars);
         verifyLogicalOrUltraHighResCameraMetadata(name, device, chars, cameraDeviceNames);
 
         ASSERT_TRUE(ret.isOk());
diff --git a/camera/provider/aidl/vts/camera_aidl_test.cpp b/camera/provider/aidl/vts/camera_aidl_test.cpp
index 5f9d605..6a17453 100644
--- a/camera/provider/aidl/vts/camera_aidl_test.cpp
+++ b/camera/provider/aidl/vts/camera_aidl_test.cpp
@@ -831,6 +831,90 @@
     ASSERT_TRUE(hasBokehStillCaptureMode || hasBokehContinuousMode || hasVendorMode);
 }
 
+void CameraAidlTest::verifyHighSpeedRecordingCharacteristics(const std::string& cameraName,
+                                                             const CameraMetadata& chars) {
+    const camera_metadata_t* metadata =
+            reinterpret_cast<const camera_metadata_t*>(chars.metadata.data());
+
+    // Check capabilities
+    bool hasHighSpeedRecordingCapability = false;
+    bool hasUltraHighResolutionCapability = false;
+    camera_metadata_ro_entry entry;
+    int rc =
+            find_camera_metadata_ro_entry(metadata, ANDROID_REQUEST_AVAILABLE_CAPABILITIES, &entry);
+    if ((0 == rc) && (entry.count > 0)) {
+        hasHighSpeedRecordingCapability =
+                std::find(entry.data.u8, entry.data.u8 + entry.count,
+                          ANDROID_REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO) !=
+                entry.data.u8 + entry.count;
+
+        hasUltraHighResolutionCapability =
+                std::find(entry.data.u8, entry.data.u8 + entry.count,
+                          ANDROID_REQUEST_AVAILABLE_CAPABILITIES_ULTRA_HIGH_RESOLUTION_SENSOR) !=
+                entry.data.u8 + entry.count;
+    }
+
+    // Check high speed video configurations
+    camera_metadata_ro_entry highSpeedEntry;
+    rc = find_camera_metadata_ro_entry(
+            metadata, ANDROID_CONTROL_AVAILABLE_HIGH_SPEED_VIDEO_CONFIGURATIONS, &highSpeedEntry);
+    bool hasHighSpeedEntry = (0 == rc && highSpeedEntry.count > 0);
+
+    camera_metadata_ro_entry highSpeedMaxResEntry;
+    rc = find_camera_metadata_ro_entry(
+            metadata, ANDROID_CONTROL_AVAILABLE_HIGH_SPEED_VIDEO_CONFIGURATIONS_MAXIMUM_RESOLUTION,
+            &highSpeedMaxResEntry);
+    bool hasHighSpeedMaxResEntry = (0 == rc && highSpeedMaxResEntry.count > 0);
+
+    // High speed recording configuration entry must be available based on capabilities
+    bool noHighSpeedRecording =
+            !hasHighSpeedRecordingCapability && !hasHighSpeedEntry && !hasHighSpeedMaxResEntry;
+    if (noHighSpeedRecording) {
+        return;
+    }
+    bool hasHighSpeedRecording = hasHighSpeedRecordingCapability && hasHighSpeedEntry &&
+                                 ((hasHighSpeedMaxResEntry && hasUltraHighResolutionCapability) ||
+                                  !hasHighSpeedMaxResEntry);
+    ASSERT_TRUE(hasHighSpeedRecording);
+
+    std::string version, cameraId;
+    ASSERT_TRUE(matchDeviceName(cameraName, mProviderType, &version, &cameraId));
+    bool needBatchSizeCheck = (version != CAMERA_DEVICE_API_VERSION_1);
+
+    // Check each entry item
+    ASSERT_TRUE(highSpeedEntry.count > 0 && highSpeedEntry.count % 5 == 0);
+    for (auto i = 4; i < highSpeedEntry.count; i += 5) {
+        int32_t fps_min = highSpeedEntry.data.i32[i - 2];
+        int32_t fps_max = highSpeedEntry.data.i32[i - 1];
+        int32_t batch_size_max = highSpeedEntry.data.i32[i];
+        int32_t allowedMaxBatchSize = fps_max / 30;
+
+        ASSERT_GE(fps_max, 120);
+        ASSERT_TRUE(fps_min % 30 == 0 && fps_max % 30 == 0);
+        if (needBatchSizeCheck) {
+            ASSERT_LE(batch_size_max, 32);
+            ASSERT_TRUE(allowedMaxBatchSize % batch_size_max == 0);
+        }
+    }
+
+    if (hasHighSpeedMaxResEntry) {
+        ASSERT_TRUE(highSpeedMaxResEntry.count > 0 && highSpeedMaxResEntry.count % 5 == 0);
+        for (auto i = 4; i < highSpeedMaxResEntry.count; i += 5) {
+            int32_t fps_min = highSpeedMaxResEntry.data.i32[i - 2];
+            int32_t fps_max = highSpeedMaxResEntry.data.i32[i - 1];
+            int32_t batch_size_max = highSpeedMaxResEntry.data.i32[i];
+            int32_t allowedMaxBatchSize = fps_max / 30;
+
+            ASSERT_GE(fps_max, 120);
+            ASSERT_TRUE(fps_min % 30 == 0 && fps_max % 30 == 0);
+            if (needBatchSizeCheck) {
+                ASSERT_LE(batch_size_max, 32);
+                ASSERT_TRUE(allowedMaxBatchSize % batch_size_max == 0);
+            }
+        }
+    }
+}
+
 Status CameraAidlTest::getAvailableOutputStreams(const camera_metadata_t* staticMeta,
                                                  std::vector<AvailableStream>& outputStreams,
                                                  const AvailableStream* threshold,
diff --git a/camera/provider/aidl/vts/camera_aidl_test.h b/camera/provider/aidl/vts/camera_aidl_test.h
index 6f8f380..3018d5a 100644
--- a/camera/provider/aidl/vts/camera_aidl_test.h
+++ b/camera/provider/aidl/vts/camera_aidl_test.h
@@ -253,6 +253,9 @@
 
     static void verifyExtendedSceneModeCharacteristics(const camera_metadata_t* metadata);
 
+    void verifyHighSpeedRecordingCharacteristics(const std::string& cameraName,
+                                                 const CameraMetadata& chars);
+
     static void verifyZoomCharacteristics(const camera_metadata_t* metadata);
 
     static void verifyRecommendedConfigs(const CameraMetadata& chars);
@@ -610,6 +613,8 @@
 namespace {
 // device@<major>.<minor>/<type>/id
 const char* kDeviceNameRE = "device@([0-9]+\\.[0-9]+)/\\s+/(.+)";
+const std::string CAMERA_DEVICE_API_VERSION_1 = "1.1";
+
 const int32_t kMaxVideoWidth = 4096;
 const int32_t kMaxVideoHeight = 2160;
 
diff --git a/camera/provider/default/ExternalCameraProvider.cpp b/camera/provider/default/ExternalCameraProvider.cpp
index 4d2c847..54875ab 100644
--- a/camera/provider/default/ExternalCameraProvider.cpp
+++ b/camera/provider/default/ExternalCameraProvider.cpp
@@ -75,15 +75,15 @@
 
 ndk::ScopedAStatus ExternalCameraProvider::setCallback(
         const std::shared_ptr<ICameraProviderCallback>& in_callback) {
+    if (in_callback == nullptr) {
+        return fromStatus(Status::ILLEGAL_ARGUMENT);
+    }
+
     {
         Mutex::Autolock _l(mLock);
         mCallback = in_callback;
     }
 
-    if (mCallback == nullptr) {
-        return fromStatus(Status::OK);
-    }
-
     for (const auto& pair : mCameraStatusMap) {
         mCallback->cameraDeviceStatusChange(pair.first, pair.second);
     }
diff --git a/cas/1.0/default/DescramblerImpl.cpp b/cas/1.0/default/DescramblerImpl.cpp
index 6b730eb..6d7c304 100644
--- a/cas/1.0/default/DescramblerImpl.cpp
+++ b/cas/1.0/default/DescramblerImpl.cpp
@@ -79,7 +79,7 @@
         return false;
     }
 
-    return holder->requiresSecureDecoderComponent(String8(mime.c_str()));
+    return holder->requiresSecureDecoderComponent(mime.c_str());
 }
 
 static inline bool validateRangeForSize(
diff --git a/cas/1.0/default/TypeConvert.cpp b/cas/1.0/default/TypeConvert.cpp
index cd0efdb..cc25cf5 100644
--- a/cas/1.0/default/TypeConvert.cpp
+++ b/cas/1.0/default/TypeConvert.cpp
@@ -82,7 +82,7 @@
     for (size_t i = 0; i < sessionId.size(); i++) {
         result.appendFormat("%02x ", sessionId[i]);
     }
-    if (result.isEmpty()) {
+    if (result.empty()) {
         result.append("(null)");
     }
     return result;
diff --git a/cas/1.0/vts/functional/OWNERS b/cas/1.0/vts/functional/OWNERS
deleted file mode 100644
index 7d8c2ee..0000000
--- a/cas/1.0/vts/functional/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 1344
-include ../../../1.2/vts/functional/OWNERS
diff --git a/cas/1.1/default/DescramblerImpl.cpp b/cas/1.1/default/DescramblerImpl.cpp
index 9d2ead7..237d56b 100644
--- a/cas/1.1/default/DescramblerImpl.cpp
+++ b/cas/1.1/default/DescramblerImpl.cpp
@@ -75,7 +75,7 @@
         return false;
     }
 
-    return holder->requiresSecureDecoderComponent(String8(mime.c_str()));
+    return holder->requiresSecureDecoderComponent(mime.c_str());
 }
 
 static inline bool validateRangeForSize(uint64_t offset, uint64_t length, uint64_t size) {
diff --git a/cas/1.1/default/TypeConvert.cpp b/cas/1.1/default/TypeConvert.cpp
index 09ef41a..2ffc79a 100644
--- a/cas/1.1/default/TypeConvert.cpp
+++ b/cas/1.1/default/TypeConvert.cpp
@@ -81,7 +81,7 @@
     for (size_t i = 0; i < sessionId.size(); i++) {
         result.appendFormat("%02x ", sessionId[i]);
     }
-    if (result.isEmpty()) {
+    if (result.empty()) {
         result.append("(null)");
     }
     return result;
diff --git a/cas/1.1/vts/functional/OWNERS b/cas/1.1/vts/functional/OWNERS
deleted file mode 100644
index 7d8c2ee..0000000
--- a/cas/1.1/vts/functional/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 1344
-include ../../../1.2/vts/functional/OWNERS
diff --git a/cas/1.2/default/DescramblerImpl.cpp b/cas/1.2/default/DescramblerImpl.cpp
index 9d2ead7..237d56b 100644
--- a/cas/1.2/default/DescramblerImpl.cpp
+++ b/cas/1.2/default/DescramblerImpl.cpp
@@ -75,7 +75,7 @@
         return false;
     }
 
-    return holder->requiresSecureDecoderComponent(String8(mime.c_str()));
+    return holder->requiresSecureDecoderComponent(mime.c_str());
 }
 
 static inline bool validateRangeForSize(uint64_t offset, uint64_t length, uint64_t size) {
diff --git a/cas/1.2/default/TypeConvert.cpp b/cas/1.2/default/TypeConvert.cpp
index c4bd0dd..7d27fa1 100644
--- a/cas/1.2/default/TypeConvert.cpp
+++ b/cas/1.2/default/TypeConvert.cpp
@@ -108,7 +108,7 @@
     for (size_t i = 0; i < sessionId.size(); i++) {
         result.appendFormat("%02x ", sessionId[i]);
     }
-    if (result.isEmpty()) {
+    if (result.empty()) {
         result.append("(null)");
     }
     return result;
diff --git a/cas/1.2/vts/functional/OWNERS b/cas/1.2/vts/functional/OWNERS
deleted file mode 100644
index 4c55752..0000000
--- a/cas/1.2/vts/functional/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-# Bug component: 1344
-quxiangfang@google.com
-hgchen@google.com
diff --git a/cas/OWNERS b/cas/OWNERS
index 473c8f26..f6c60aa 100644
--- a/cas/OWNERS
+++ b/cas/OWNERS
@@ -1 +1,4 @@
-include /tv/input/OWNERS
+# Bug component: 1344
+
+hgchen@google.com
+quxiangfang@google.com
\ No newline at end of file
diff --git a/cas/aidl/default/Android.bp b/cas/aidl/default/Android.bp
index 576016e..9d094e0 100644
--- a/cas/aidl/default/Android.bp
+++ b/cas/aidl/default/Android.bp
@@ -26,6 +26,7 @@
         "liblog",
         "libutils",
         "libcutils",
+        "libvndksupport",
     ],
     static_libs: [
         "libaidlcommonsupport",
@@ -43,34 +44,39 @@
 
     srcs: ["service.cpp"],
 
+    stl: "c++_static",
     static_libs: [
+        "android.hardware.cas-V1-ndk",
+        "android.hardware.common-V2-ndk",
         "libaidlcommonsupport",
+        "libbase",
         "libcasexampleimpl",
+        "libcutils",
+        "libutils",
     ],
     shared_libs: [
-        "android.hardware.cas-V1-ndk",
-        "libbase",
         "libbinder_ndk",
         "liblog",
-        "libutils",
-        "libcutils",
+        "libvndksupport",
     ],
     header_libs: ["media_plugin_headers"],
-    vintf_fragments: ["android.hardware.cas-service.xml"],
 }
 
 cc_binary {
     name: "android.hardware.cas-service.example",
     defaults: ["cas_service_example_defaults"],
-    init_rc: ["cas-default.rc"],
+    // Installed in APEX
+    installable: false,
 }
 
+// TODO(b/297467514) Convert to VAPEX
 cc_binary {
     name: "android.hardware.cas-service.example-lazy",
     defaults: ["cas_service_example_defaults"],
     init_rc: ["cas-default-lazy.rc"],
+    vintf_fragments: ["android.hardware.cas-service.xml"],
     cflags: ["-DLAZY_SERVICE"],
-    overrides: ["android.hardware.cas-service.example"],
+    overrides: ["com.android.hardware.cas"],
 }
 
 cc_fuzz {
@@ -84,6 +90,7 @@
         "android.hardware.cas-V1-ndk",
         "libcutils",
         "liblog",
+        "libvndksupport",
     ],
     static_libs: [
         "libaidlcommonsupport",
@@ -94,3 +101,34 @@
         componentid: 1344,
     },
 }
+
+apex {
+    name: "com.android.hardware.cas",
+    manifest: "manifest.json",
+    file_contexts: "file_contexts",
+    key: "com.android.hardware.key",
+    certificate: ":com.android.hardware.certificate",
+    updatable: false,
+    vendor: true,
+
+    binaries: [
+        "android.hardware.cas-service.example",
+    ],
+    prebuilts: [
+        "cas-default.rc",
+        "android.hardware.cas-service.xml",
+    ],
+}
+
+prebuilt_etc {
+    name: "cas-default.rc",
+    src: "cas-default.rc",
+    installable: false,
+}
+
+prebuilt_etc {
+    name: "android.hardware.cas-service.xml",
+    src: "android.hardware.cas-service.xml",
+    sub_dir: "vintf",
+    installable: false,
+}
diff --git a/cas/aidl/default/DescramblerImpl.cpp b/cas/aidl/default/DescramblerImpl.cpp
index d658887..0f4e99b 100644
--- a/cas/aidl/default/DescramblerImpl.cpp
+++ b/cas/aidl/default/DescramblerImpl.cpp
@@ -71,7 +71,7 @@
         *_aidl_return = false;
     }
 
-    *_aidl_return = holder->requiresSecureDecoderComponent(String8(in_mime.c_str()));
+    *_aidl_return = holder->requiresSecureDecoderComponent(in_mime.c_str());
     return ScopedAStatus::ok();
 }
 
diff --git a/cas/aidl/default/SharedLibrary.cpp b/cas/aidl/default/SharedLibrary.cpp
index c12d17d..6322ff3 100644
--- a/cas/aidl/default/SharedLibrary.cpp
+++ b/cas/aidl/default/SharedLibrary.cpp
@@ -19,6 +19,7 @@
 #include "SharedLibrary.h"
 #include <dlfcn.h>
 #include <utils/Log.h>
+#include <vndksupport/linker.h>
 
 namespace aidl {
 namespace android {
@@ -26,12 +27,12 @@
 namespace cas {
 
 SharedLibrary::SharedLibrary(const String8& path) {
-    mLibHandle = dlopen(path.c_str(), RTLD_NOW);
+    mLibHandle = android_load_sphal_library(path.c_str(), RTLD_NOW);
 }
 
 SharedLibrary::~SharedLibrary() {
     if (mLibHandle != NULL) {
-        dlclose(mLibHandle);
+        android_unload_sphal_library(mLibHandle);
         mLibHandle = NULL;
     }
 }
diff --git a/cas/aidl/default/cas-default.rc b/cas/aidl/default/cas-default.rc
index 5a60368..0ac7fe5 100644
--- a/cas/aidl/default/cas-default.rc
+++ b/cas/aidl/default/cas-default.rc
@@ -1,4 +1,4 @@
-service vendor.cas-default /vendor/bin/hw/android.hardware.cas-service.example
+service vendor.cas-default /apex/com.android.hardware.cas/bin/hw/android.hardware.cas-service.example
     interface aidl android.hardware.cas.IMediaCasService/default
     class hal
     user media
diff --git a/cas/aidl/default/file_contexts b/cas/aidl/default/file_contexts
new file mode 100644
index 0000000..98bde53
--- /dev/null
+++ b/cas/aidl/default/file_contexts
@@ -0,0 +1,3 @@
+(/.*)?                                                          u:object_r:vendor_file:s0
+/etc(/.*)?                                                      u:object_r:vendor_configs_file:s0
+/bin/hw/android\.hardware\.cas-service\.example                 u:object_r:hal_cas_default_exec:s0
diff --git a/cas/aidl/default/manifest.json b/cas/aidl/default/manifest.json
new file mode 100644
index 0000000..16b4f67
--- /dev/null
+++ b/cas/aidl/default/manifest.json
@@ -0,0 +1,9 @@
+{
+    "name": "com.android.hardware.cas",
+    "version": 1,
+    // For CAS HAL to open plugins from /vendor/lib, "vendor" namespace should be imported.
+    // ":sphal" is an alias for the "vendor" namespace in Vendor APEX.
+    "requireNativeLibs": [
+        ":sphal"
+    ]
+}
diff --git a/cas/aidl/vts/functional/OWNERS b/cas/aidl/vts/functional/OWNERS
deleted file mode 100644
index 4c55752..0000000
--- a/cas/aidl/vts/functional/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-# Bug component: 1344
-quxiangfang@google.com
-hgchen@google.com
diff --git a/common/OWNERS b/common/OWNERS
new file mode 100644
index 0000000..a07824e
--- /dev/null
+++ b/common/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 298954331
+
+include platform/hardware/interfaces:/OWNERS
diff --git a/common/fmq/aidl/Android.bp b/common/fmq/aidl/Android.bp
index 3b022fc..6c37213 100644
--- a/common/fmq/aidl/Android.bp
+++ b/common/fmq/aidl/Android.bp
@@ -43,8 +43,9 @@
             min_sdk_version: "29",
         },
         rust: {
-            // FMQ is not supported in the rust backend
-            enabled: false,
+            // FMQ is not supported in the rust backend, but we need this AIDL interface for
+            // HardwareBuffer.
+            enabled: true,
         },
     },
     frozen: true,
diff --git a/compatibility_matrices/Android.mk b/compatibility_matrices/Android.mk
index f1dd956..c2ffb84 100644
--- a/compatibility_matrices/Android.mk
+++ b/compatibility_matrices/Android.mk
@@ -56,6 +56,9 @@
 
 endif # DEVICE_FRAMEWORK_COMPATIBILITY_MATRIX_FILE
 
+# TODO(b/296875906): use POLICYVERS from Soong
+POLICYVERS ?= 30
+
 LOCAL_ADD_VBMETA_VERSION := true
 LOCAL_ASSEMBLE_VINTF_ENV_VARS := \
     POLICYVERS \
diff --git a/compatibility_matrices/OWNERS b/compatibility_matrices/OWNERS
new file mode 100644
index 0000000..a07824e
--- /dev/null
+++ b/compatibility_matrices/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 298954331
+
+include platform/hardware/interfaces:/OWNERS
diff --git a/compatibility_matrices/compatibility_matrix.7.xml b/compatibility_matrices/compatibility_matrix.7.xml
index 14c330e..fe424bd 100644
--- a/compatibility_matrices/compatibility_matrix.7.xml
+++ b/compatibility_matrices/compatibility_matrix.7.xml
@@ -404,7 +404,7 @@
     </hal>
     <hal format="aidl" optional="true">
         <name>android.hardware.light</name>
-        <version>2</version>
+        <version>1-2</version>
         <interface>
             <name>ILights</name>
             <instance>default</instance>
diff --git a/compatibility_matrices/compatibility_matrix.8.xml b/compatibility_matrices/compatibility_matrix.8.xml
index 9e3b8f9..2a1f4a5 100644
--- a/compatibility_matrices/compatibility_matrix.8.xml
+++ b/compatibility_matrices/compatibility_matrix.8.xml
@@ -120,6 +120,7 @@
         <interface>
             <name>IFace</name>
             <instance>default</instance>
+            <instance>virtual</instance>
         </interface>
     </hal>
     <hal format="aidl" optional="true" updatable-via-apex="true">
diff --git a/compatibility_matrices/compatibility_matrix.9.xml b/compatibility_matrices/compatibility_matrix.9.xml
index 9a9af1c..0013923 100644
--- a/compatibility_matrices/compatibility_matrix.9.xml
+++ b/compatibility_matrices/compatibility_matrix.9.xml
@@ -102,6 +102,7 @@
     </hal>
     <hal format="aidl" optional="true">
         <name>android.hardware.automotive.remoteaccess</name>
+        <version>1-2</version>
         <interface>
             <name>IRemoteAccess</name>
             <instance>default</instance>
@@ -120,6 +121,7 @@
         <interface>
             <name>IFace</name>
             <instance>default</instance>
+            <instance>virtual</instance>
         </interface>
     </hal>
     <hal format="aidl" optional="true" updatable-via-apex="true">
diff --git a/configstore/1.0/vts/functional/OWNERS b/configstore/OWNERS
similarity index 97%
rename from configstore/1.0/vts/functional/OWNERS
rename to configstore/OWNERS
index edfa1b0..70ad434 100644
--- a/configstore/1.0/vts/functional/OWNERS
+++ b/configstore/OWNERS
@@ -1,2 +1,3 @@
 # Bug component: 24939
+
 lpy@google.com
diff --git a/contexthub/aidl/default/Android.bp b/contexthub/aidl/default/Android.bp
index 74bac69..03213bc 100644
--- a/contexthub/aidl/default/Android.bp
+++ b/contexthub/aidl/default/Android.bp
@@ -57,3 +57,34 @@
     ],
     srcs: ["main.cpp"],
 }
+
+prebuilt_etc {
+    name: "android.hardware.contexthub-service.example.rc",
+    src: "android.hardware.contexthub-service.example.rc",
+    installable: false,
+}
+
+prebuilt_etc {
+    name: "contexthub-default.xml",
+    src: "contexthub-default.xml",
+    sub_dir: "vintf",
+    installable: false,
+}
+
+apex {
+    name: "com.android.hardware.contexthub",
+    vendor: true,
+    manifest: "apex_manifest.json",
+    file_contexts: "apex_file_contexts",
+    key: "com.android.hardware.key",
+    certificate: ":com.android.hardware.certificate",
+    updatable: false,
+
+    binaries: [
+        "android.hardware.contexthub-service.example",
+    ],
+    prebuilts: [
+        "android.hardware.contexthub-service.example.rc",
+        "contexthub-default.xml",
+    ],
+}
diff --git a/contexthub/aidl/default/android.hardware.contexthub-service.example.rc b/contexthub/aidl/default/android.hardware.contexthub-service.example.rc
new file mode 100644
index 0000000..7d5d2aa
--- /dev/null
+++ b/contexthub/aidl/default/android.hardware.contexthub-service.example.rc
@@ -0,0 +1,4 @@
+service vendor.contexthub-default /apex/com.android.hardware.contexthub/bin/hw/android.hardware.contexthub-service.example
+    class hal
+    user context_hub
+    group context_hub
diff --git a/contexthub/aidl/default/apex_file_contexts b/contexthub/aidl/default/apex_file_contexts
new file mode 100644
index 0000000..c3c67df
--- /dev/null
+++ b/contexthub/aidl/default/apex_file_contexts
@@ -0,0 +1,3 @@
+(/.*)?                                                          u:object_r:vendor_file:s0
+/etc(/.*)?                                                      u:object_r:vendor_configs_file:s0
+/bin/hw/android\.hardware\.contexthub-service\.example          u:object_r:hal_contexthub_default_exec:s0
diff --git a/contexthub/aidl/default/apex_manifest.json b/contexthub/aidl/default/apex_manifest.json
new file mode 100644
index 0000000..aed7081
--- /dev/null
+++ b/contexthub/aidl/default/apex_manifest.json
@@ -0,0 +1,4 @@
+{
+    "name": "com.android.hardware.contexthub",
+    "version": 1
+}
\ No newline at end of file
diff --git a/drm/1.0/default/DrmPlugin.cpp b/drm/1.0/default/DrmPlugin.cpp
index dfa5d22..0a0a350 100644
--- a/drm/1.0/default/DrmPlugin.cpp
+++ b/drm/1.0/default/DrmPlugin.cpp
@@ -133,8 +133,8 @@
         Vector<KeyValue> infoMapVec;
         for (size_t i = 0; i < legacyInfoMap.size(); i++) {
             KeyValue keyValuePair;
-            keyValuePair.key = String8(legacyInfoMap.keyAt(i));
-            keyValuePair.value = String8(legacyInfoMap.valueAt(i));
+            keyValuePair.key = legacyInfoMap.keyAt(i);
+            keyValuePair.value = legacyInfoMap.valueAt(i);
             infoMapVec.push_back(keyValuePair);
         }
         _hidl_cb(toStatus(status), toHidlVec(infoMapVec));
diff --git a/drm/1.0/default/OWNERS b/drm/1.0/default/OWNERS
deleted file mode 100644
index ecb421c..0000000
--- a/drm/1.0/default/OWNERS
+++ /dev/null
@@ -1,6 +0,0 @@
-edwinwong@google.com
-fredgc@google.com
-jtinker@google.com
-kylealexander@google.com
-rfrias@google.com
-robertshih@google.com
diff --git a/drm/1.0/default/include/PluginLoader.h b/drm/1.0/default/include/PluginLoader.h
index 5130b16..a25dd41 100644
--- a/drm/1.0/default/include/PluginLoader.h
+++ b/drm/1.0/default/include/PluginLoader.h
@@ -50,7 +50,7 @@
                 String8 file(pEntry->d_name);
                 if (base::EndsWith(file.c_str(), ".so")) {
                     String8 path = pluginDir + "/" + pEntry->d_name;
-                    T *plugin = loadOne(path, entry);
+                    T* plugin = loadOne(path.c_str(), entry);
                     if (plugin) {
                         factories.push(plugin);
                     }
diff --git a/drm/1.0/vts/OWNERS b/drm/1.0/vts/OWNERS
deleted file mode 100644
index ecb421c..0000000
--- a/drm/1.0/vts/OWNERS
+++ /dev/null
@@ -1,6 +0,0 @@
-edwinwong@google.com
-fredgc@google.com
-jtinker@google.com
-kylealexander@google.com
-rfrias@google.com
-robertshih@google.com
diff --git a/drm/1.0/vts/functional/Android.bp b/drm/1.0/vts/functional/Android.bp
index d6c37c5..e0c6fa5 100644
--- a/drm/1.0/vts/functional/Android.bp
+++ b/drm/1.0/vts/functional/Android.bp
@@ -111,13 +111,13 @@
             data: [":libvtswidevine-arm-prebuilts"],
         },
         arm64: {
-            data: [":libvtswidevine-arm64-prebuilts"],
+            data: [":libvtswidevine-arm64-prebuilts",":libvtswidevine-arm-prebuilts"],
         },
         x86: {
             data: [":libvtswidevine-x86-prebuilts"],
         },
         x86_64: {
-            data: [":libvtswidevine-x86_64-prebuilts"],
+            data: [":libvtswidevine-x86_64-prebuilts",":libvtswidevine-x86-prebuilts"],
         },
     },
     test_suites: [
diff --git a/drm/1.0/vts/functional/OWNERS b/drm/1.0/vts/functional/OWNERS
deleted file mode 100644
index 0b13790..0000000
--- a/drm/1.0/vts/functional/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-# Bug component: 49079
-jtinker@google.com
-robertshih@google.com
-edwinwong@google.com
\ No newline at end of file
diff --git a/drm/1.1/vts/OWNERS b/drm/1.1/vts/OWNERS
deleted file mode 100644
index ecb421c..0000000
--- a/drm/1.1/vts/OWNERS
+++ /dev/null
@@ -1,6 +0,0 @@
-edwinwong@google.com
-fredgc@google.com
-jtinker@google.com
-kylealexander@google.com
-rfrias@google.com
-robertshih@google.com
diff --git a/drm/1.1/vts/functional/Android.bp b/drm/1.1/vts/functional/Android.bp
index 760b67e..b539fa2 100644
--- a/drm/1.1/vts/functional/Android.bp
+++ b/drm/1.1/vts/functional/Android.bp
@@ -82,13 +82,13 @@
             data: [":libvtswidevine-arm-prebuilts"],
         },
         arm64: {
-            data: [":libvtswidevine-arm64-prebuilts"],
+            data: [":libvtswidevine-arm64-prebuilts",":libvtswidevine-arm-prebuilts"],
         },
         x86: {
             data: [":libvtswidevine-x86-prebuilts"],
         },
         x86_64: {
-            data: [":libvtswidevine-x86_64-prebuilts"],
+            data: [":libvtswidevine-x86_64-prebuilts",":libvtswidevine-x86-prebuilts"],
         },
     },
     test_suites: [
diff --git a/drm/1.1/vts/functional/OWNERS b/drm/1.1/vts/functional/OWNERS
deleted file mode 100644
index 0b13790..0000000
--- a/drm/1.1/vts/functional/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-# Bug component: 49079
-jtinker@google.com
-robertshih@google.com
-edwinwong@google.com
\ No newline at end of file
diff --git a/drm/1.2/vts/OWNERS b/drm/1.2/vts/OWNERS
deleted file mode 100644
index ecb421c..0000000
--- a/drm/1.2/vts/OWNERS
+++ /dev/null
@@ -1,6 +0,0 @@
-edwinwong@google.com
-fredgc@google.com
-jtinker@google.com
-kylealexander@google.com
-rfrias@google.com
-robertshih@google.com
diff --git a/drm/1.2/vts/functional/Android.bp b/drm/1.2/vts/functional/Android.bp
index 9a45051..9ceb1a3 100644
--- a/drm/1.2/vts/functional/Android.bp
+++ b/drm/1.2/vts/functional/Android.bp
@@ -100,13 +100,13 @@
             data: [":libvtswidevine-arm-prebuilts"],
         },
         arm64: {
-            data: [":libvtswidevine-arm64-prebuilts"],
+            data: [":libvtswidevine-arm64-prebuilts",":libvtswidevine-arm-prebuilts"],
         },
         x86: {
             data: [":libvtswidevine-x86-prebuilts"],
         },
         x86_64: {
-            data: [":libvtswidevine-x86_64-prebuilts"],
+            data: [":libvtswidevine-x86_64-prebuilts",":libvtswidevine-x86-prebuilts"],
         },
     },
     test_suites: [
diff --git a/drm/1.2/vts/functional/OWNERS b/drm/1.2/vts/functional/OWNERS
deleted file mode 100644
index 0b13790..0000000
--- a/drm/1.2/vts/functional/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-# Bug component: 49079
-jtinker@google.com
-robertshih@google.com
-edwinwong@google.com
\ No newline at end of file
diff --git a/drm/1.3/vts/functional/Android.bp b/drm/1.3/vts/functional/Android.bp
index cd1cc0f..3db23e3 100644
--- a/drm/1.3/vts/functional/Android.bp
+++ b/drm/1.3/vts/functional/Android.bp
@@ -85,13 +85,13 @@
             data: [":libvtswidevine-arm-prebuilts"],
         },
         arm64: {
-            data: [":libvtswidevine-arm64-prebuilts"],
+            data: [":libvtswidevine-arm64-prebuilts",":libvtswidevine-arm-prebuilts"],
         },
         x86: {
             data: [":libvtswidevine-x86-prebuilts"],
         },
         x86_64: {
-            data: [":libvtswidevine-x86_64-prebuilts"],
+            data: [":libvtswidevine-x86_64-prebuilts",":libvtswidevine-x86-prebuilts"],
         },
     },
     test_suites: [
diff --git a/drm/1.4/vts/OWNERS b/drm/1.4/vts/OWNERS
deleted file mode 100644
index 3a0672e..0000000
--- a/drm/1.4/vts/OWNERS
+++ /dev/null
@@ -1,9 +0,0 @@
-conglin@google.com
-edwinwong@google.com
-fredgc@google.com
-jtinker@google.com
-juce@google.com
-kylealexander@google.com
-rfrias@google.com
-robertshih@google.com
-sigquit@google.com
diff --git a/drm/1.4/vts/functional/Android.bp b/drm/1.4/vts/functional/Android.bp
index e18d088..89edab7 100644
--- a/drm/1.4/vts/functional/Android.bp
+++ b/drm/1.4/vts/functional/Android.bp
@@ -88,13 +88,13 @@
             data: [":libvtswidevine-arm-prebuilts"],
         },
         arm64: {
-            data: [":libvtswidevine-arm64-prebuilts"],
+            data: [":libvtswidevine-arm64-prebuilts",":libvtswidevine-arm-prebuilts"],
         },
         x86: {
             data: [":libvtswidevine-x86-prebuilts"],
         },
         x86_64: {
-            data: [":libvtswidevine-x86_64-prebuilts"],
+            data: [":libvtswidevine-x86_64-prebuilts",":libvtswidevine-x86-prebuilts"],
         },
     },
     test_suites: [
diff --git a/drm/1.3/vts/OWNERS b/drm/OWNERS
similarity index 98%
rename from drm/1.3/vts/OWNERS
rename to drm/OWNERS
index 744827c..c06472a 100644
--- a/drm/1.3/vts/OWNERS
+++ b/drm/OWNERS
@@ -1,4 +1,5 @@
 # Bug component: 49079
+
 conglin@google.com
 fredgc@google.com
 juce@google.com
@@ -8,4 +9,4 @@
 rfrias@google.com
 robertshih@google.com
 sigquit@google.com
-vickymin@google.com
\ No newline at end of file
+vickymin@google.com
diff --git a/drm/aidl/OWNERS b/drm/aidl/OWNERS
index fe69725..e69de29 100644
--- a/drm/aidl/OWNERS
+++ b/drm/aidl/OWNERS
@@ -1,3 +0,0 @@
-# Bug component: 49079
-kelzhan@google.com
-robertshih@google.com
diff --git a/drm/aidl/vts/Android.bp b/drm/aidl/vts/Android.bp
index 190f60d..5139036 100644
--- a/drm/aidl/vts/Android.bp
+++ b/drm/aidl/vts/Android.bp
@@ -59,13 +59,13 @@
             data: [":libvtswidevine-arm-prebuilts"],
         },
         arm64: {
-            data: [":libvtswidevine-arm64-prebuilts"],
+            data: [":libvtswidevine-arm64-prebuilts", ":libvtswidevine-arm-prebuilts"],
         },
         x86: {
             data: [":libvtswidevine-x86-prebuilts"],
         },
         x86_64: {
-            data: [":libvtswidevine-x86_64-prebuilts"],
+            data: [":libvtswidevine-x86_64-prebuilts", ":libvtswidevine-x86-prebuilts"],
         },
     },
     test_suites: [
diff --git a/drm/aidl/vts/OWNERS b/drm/aidl/vts/OWNERS
index fe69725..e69de29 100644
--- a/drm/aidl/vts/OWNERS
+++ b/drm/aidl/vts/OWNERS
@@ -1,3 +0,0 @@
-# Bug component: 49079
-kelzhan@google.com
-robertshih@google.com
diff --git a/dumpstate/OWNERS b/dumpstate/OWNERS
new file mode 100644
index 0000000..4c9173e
--- /dev/null
+++ b/dumpstate/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 298624585
+
+include platform/frameworks/native:/cmds/dumpstate/OWNERS
diff --git a/dumpstate/aidl/default/Android.bp b/dumpstate/aidl/default/Android.bp
index 45fdc17..a9da69c 100644
--- a/dumpstate/aidl/default/Android.bp
+++ b/dumpstate/aidl/default/Android.bp
@@ -44,3 +44,41 @@
         "-DLOG_TAG=\"android.hardware.dumpstate-service.example\"",
     ],
 }
+
+prebuilt_etc {
+    name: "dumpstate-default.xml",
+    src: "dumpstate-default.xml",
+    sub_dir: "vintf",
+    installable: false,
+}
+
+prebuilt_etc {
+    name: "dumpstate-default.rc",
+    src: ":gen-dumpstate-default.rc-for-apex",
+    installable: false,
+}
+
+genrule {
+    name: "gen-dumpstate-default.rc-for-apex",
+    srcs: ["dumpstate-default.rc"],
+    out: ["dumpstate-default-apex.rc"],
+    cmd: "sed -E 's/\\/vendor\\/bin\\/hw/\\/apex\\/com.android.hardware.dumpstate\\/bin\\/hw/' $(in) > $(out)",
+}
+
+apex {
+    name: "com.android.hardware.dumpstate",
+    vendor: true,
+    manifest: "apex_manifest.json",
+    file_contexts: "apex_file_contexts",
+    key: "com.android.hardware.key",
+    certificate: ":com.android.hardware.certificate",
+    updatable: false,
+
+    binaries: [
+        "android.hardware.dumpstate-service.example",
+    ],
+    prebuilts: [
+        "dumpstate-default.rc",
+        "dumpstate-default.xml",
+    ],
+}
diff --git a/dumpstate/aidl/default/apex_file_contexts b/dumpstate/aidl/default/apex_file_contexts
new file mode 100644
index 0000000..91153a9
--- /dev/null
+++ b/dumpstate/aidl/default/apex_file_contexts
@@ -0,0 +1,3 @@
+(/.*)?                                          u:object_r:vendor_file:s0
+/etc(/.*)?                                      u:object_r:vendor_configs_file:s0
+/bin/hw/android\.hardware\.dumpstate-service\.example u:object_r:hal_dumpstate_default_exec:s0
\ No newline at end of file
diff --git a/dumpstate/aidl/default/apex_manifest.json b/dumpstate/aidl/default/apex_manifest.json
new file mode 100644
index 0000000..32beea4
--- /dev/null
+++ b/dumpstate/aidl/default/apex_manifest.json
@@ -0,0 +1,4 @@
+{
+    "name": "com.android.hardware.dumpstate",
+    "version": 1
+}
\ No newline at end of file
diff --git a/gnss/1.0/default/OWNERS b/gnss/1.0/default/OWNERS
deleted file mode 100644
index 6c25bd7..0000000
--- a/gnss/1.0/default/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-wyattriley@google.com
-gomo@google.com
-smalkos@google.com
diff --git a/gnss/1.0/vts/OWNERS b/gnss/1.0/vts/OWNERS
deleted file mode 100644
index 937d70a..0000000
--- a/gnss/1.0/vts/OWNERS
+++ /dev/null
@@ -1,7 +0,0 @@
-wyattriley@google.com
-gomo@google.com
-smalkos@google.com
-
-# VTS team
-yim@google.com
-trong@google.com
\ No newline at end of file
diff --git a/gnss/1.0/vts/functional/OWNERS b/gnss/1.0/vts/functional/OWNERS
deleted file mode 100644
index b831eb4..0000000
--- a/gnss/1.0/vts/functional/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 393449
-yuhany@google.com
diff --git a/gnss/1.1/default/OWNERS b/gnss/1.1/default/OWNERS
deleted file mode 100644
index a3d8577..0000000
--- a/gnss/1.1/default/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-wyattriley@google.com
-gomo@google.com
-smalkos@google.com
-yuhany@google.com
diff --git a/gnss/1.1/vts/OWNERS b/gnss/1.1/vts/OWNERS
deleted file mode 100644
index 3ed36da..0000000
--- a/gnss/1.1/vts/OWNERS
+++ /dev/null
@@ -1,7 +0,0 @@
-wyattriley@google.com
-gomo@google.com
-smalkos@google.com
-yuhany@google.com
-
-# VTS team
-yim@google.com
diff --git a/gnss/1.1/vts/functional/OWNERS b/gnss/1.1/vts/functional/OWNERS
deleted file mode 100644
index b831eb4..0000000
--- a/gnss/1.1/vts/functional/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 393449
-yuhany@google.com
diff --git a/gnss/2.0/default/OWNERS b/gnss/2.0/default/OWNERS
deleted file mode 100644
index 8da956c..0000000
--- a/gnss/2.0/default/OWNERS
+++ /dev/null
@@ -1,5 +0,0 @@
-wyattriley@google.com
-gomo@google.com
-smalkos@google.com
-yuhany@google.com
-aadmal@google.com
diff --git a/gnss/2.0/vts/OWNERS b/gnss/2.0/vts/OWNERS
deleted file mode 100644
index 0a7ce6c..0000000
--- a/gnss/2.0/vts/OWNERS
+++ /dev/null
@@ -1,8 +0,0 @@
-wyattriley@google.com
-gomo@google.com
-smalkos@google.com
-yuhany@google.com
-aadmal@google.com
-
-# VTS team
-yim@google.com
diff --git a/gnss/2.0/vts/functional/OWNERS b/gnss/2.0/vts/functional/OWNERS
deleted file mode 100644
index b831eb4..0000000
--- a/gnss/2.0/vts/functional/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 393449
-yuhany@google.com
diff --git a/gnss/2.1/default/OWNERS b/gnss/2.1/default/OWNERS
deleted file mode 100644
index b7b4a2e..0000000
--- a/gnss/2.1/default/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-gomo@google.com
-smalkos@google.com
-wyattriley@google.com
-yuhany@google.com
diff --git a/gnss/2.1/vts/OWNERS b/gnss/2.1/vts/OWNERS
deleted file mode 100644
index b7b4a2e..0000000
--- a/gnss/2.1/vts/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-gomo@google.com
-smalkos@google.com
-wyattriley@google.com
-yuhany@google.com
diff --git a/gnss/2.1/vts/functional/OWNERS b/gnss/2.1/vts/functional/OWNERS
deleted file mode 100644
index b831eb4..0000000
--- a/gnss/2.1/vts/functional/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 393449
-yuhany@google.com
diff --git a/gnss/aidl/OWNERS b/gnss/OWNERS
similarity index 75%
rename from gnss/aidl/OWNERS
rename to gnss/OWNERS
index e5b585e..57982e7 100644
--- a/gnss/aidl/OWNERS
+++ b/gnss/OWNERS
@@ -2,5 +2,7 @@
 
 gomo@google.com
 smalkos@google.com
+trong@google.com
 wyattriley@google.com
+yim@google.com
 yuhany@google.com
diff --git a/gnss/common/OWNERS b/gnss/common/OWNERS
deleted file mode 100644
index 3ed36da..0000000
--- a/gnss/common/OWNERS
+++ /dev/null
@@ -1,7 +0,0 @@
-wyattriley@google.com
-gomo@google.com
-smalkos@google.com
-yuhany@google.com
-
-# VTS team
-yim@google.com
diff --git a/graphics/Android.bp b/graphics/Android.bp
index 8a69f09..cae5292 100644
--- a/graphics/Android.bp
+++ b/graphics/Android.bp
@@ -39,14 +39,14 @@
 cc_defaults {
     name: "android.hardware.graphics.common-ndk_static",
     static_libs: [
-        "android.hardware.graphics.common-V4-ndk",
+        "android.hardware.graphics.common-V5-ndk",
     ],
 }
 
 cc_defaults {
     name: "android.hardware.graphics.common-ndk_shared",
     shared_libs: [
-        "android.hardware.graphics.common-V4-ndk",
+        "android.hardware.graphics.common-V5-ndk",
     ],
 }
 
diff --git a/graphics/allocator/aidl/Android.bp b/graphics/allocator/aidl/Android.bp
index a3a2c55..03628b0 100644
--- a/graphics/allocator/aidl/Android.bp
+++ b/graphics/allocator/aidl/Android.bp
@@ -18,7 +18,7 @@
     srcs: ["android/hardware/graphics/allocator/*.aidl"],
     imports: [
         "android.hardware.common-V2",
-        "android.hardware.graphics.common-V4",
+        "android.hardware.graphics.common-V5",
     ],
     stability: "vintf",
     backend: {
@@ -49,7 +49,7 @@
             version: "2",
             imports: [
                 "android.hardware.common-V2",
-                "android.hardware.graphics.common-V4",
+                "android.hardware.graphics.common-V5",
             ],
         },
 
diff --git a/graphics/common/aidl/Android.bp b/graphics/common/aidl/Android.bp
index 142c7c1..f177a41 100644
--- a/graphics/common/aidl/Android.bp
+++ b/graphics/common/aidl/Android.bp
@@ -15,7 +15,7 @@
         enabled: true,
         support_system_process: true,
     },
-    vndk_use_version: "4",
+    vndk_use_version: "5",
     srcs: [
         "android/hardware/graphics/common/*.aidl",
     ],
diff --git a/graphics/common/aidl/aidl_api/android.hardware.graphics.common/current/android/hardware/graphics/common/Dataspace.aidl b/graphics/common/aidl/aidl_api/android.hardware.graphics.common/current/android/hardware/graphics/common/Dataspace.aidl
index d9ff5aa..6ed5bb2 100644
--- a/graphics/common/aidl/aidl_api/android.hardware.graphics.common/current/android/hardware/graphics/common/Dataspace.aidl
+++ b/graphics/common/aidl/aidl_api/android.hardware.graphics.common/current/android/hardware/graphics/common/Dataspace.aidl
@@ -81,9 +81,11 @@
   DISPLAY_P3_LINEAR = (((10 << 16) | (1 << 22)) | (1 << 27)) /* 139067392 */,
   DISPLAY_P3 = (((10 << 16) | (2 << 22)) | (1 << 27)) /* 143261696 */,
   ADOBE_RGB = (((11 << 16) | (4 << 22)) | (1 << 27)) /* 151715840 */,
+  ADOBE_RGB_LINEAR = (((11 << 16) | (1 << 22)) | (1 << 27)) /* 139132928 */,
   BT2020_LINEAR = (((6 << 16) | (1 << 22)) | (1 << 27)) /* 138805248 */,
   BT2020 = (((6 << 16) | (3 << 22)) | (1 << 27)) /* 147193856 */,
   BT2020_PQ = (((6 << 16) | (7 << 22)) | (1 << 27)) /* 163971072 */,
+  BT2020_LINEAR_EXTENDED = (((6 << 16) | (1 << 22)) | (3 << 27)) /* 407240704 */,
   DEPTH = 0x1000,
   SENSOR = 0x1001,
   BT2020_ITU = (((6 << 16) | (3 << 22)) | (2 << 27)) /* 281411584 */,
diff --git a/graphics/common/aidl/aidl_api/android.hardware.graphics.common/current/android/hardware/graphics/common/HardwareBuffer.aidl b/graphics/common/aidl/aidl_api/android.hardware.graphics.common/current/android/hardware/graphics/common/HardwareBuffer.aidl
index 1817769..0fe9493 100644
--- a/graphics/common/aidl/aidl_api/android.hardware.graphics.common/current/android/hardware/graphics/common/HardwareBuffer.aidl
+++ b/graphics/common/aidl/aidl_api/android.hardware.graphics.common/current/android/hardware/graphics/common/HardwareBuffer.aidl
@@ -32,7 +32,10 @@
 // later when a module using the interface is updated, e.g., Mainline modules.
 
 package android.hardware.graphics.common;
-/* @hide */
+/**
+ * @hide
+ * @deprecated : Use instead android.hardware.HardwareBuffer in frameworks/base
+ */
 @VintfStability
 parcelable HardwareBuffer {
   android.hardware.graphics.common.HardwareBufferDescription description;
diff --git a/graphics/common/aidl/android/hardware/graphics/common/Dataspace.aidl b/graphics/common/aidl/android/hardware/graphics/common/Dataspace.aidl
index 4b6613e..79737eb 100644
--- a/graphics/common/aidl/android/hardware/graphics/common/Dataspace.aidl
+++ b/graphics/common/aidl/android/hardware/graphics/common/Dataspace.aidl
@@ -559,6 +559,13 @@
     ADOBE_RGB = 11 << 16 | 4 << 22 | 1 << 27, // STANDARD_ADOBE_RGB | TRANSFER_GAMMA2_2 | RANGE_FULL
 
     /**
+     * Adobe RGB LINEAR
+     *
+     * Use full range, linear transfer and Adobe RGB primaries
+     */
+    ADOBE_RGB_LINEAR = 11 << 16 | 1 << 22 | 1 << 27, // STANDARD_ADOBE_RGB | TRANSFER_LINEAR | RANGE_FULL
+
+    /**
      * ITU-R Recommendation 2020 (BT.2020)
      *
      * Ultra High-definition television
@@ -586,6 +593,15 @@
     BT2020_PQ = 6 << 16 | 7 << 22 | 1 << 27, // STANDARD_BT2020 | TRANSFER_ST2084 | RANGE_FULL
 
     /**
+     * ITU-R Recommendation 2020 (BT.2020)
+     *
+     * Ultra High-definition television
+     *
+     * Use extended range, linear transfer and BT2020 standard
+     */
+    BT2020_LINEAR_EXTENDED = 6 << 16 | 1 << 22 | 3 << 27, // STANDARD_BT2020 | TRANSFER_LINEAR | RANGE_EXTENDED
+
+    /**
      * Data spaces for non-color formats
      */
 
diff --git a/graphics/common/aidl/android/hardware/graphics/common/HardwareBuffer.aidl b/graphics/common/aidl/android/hardware/graphics/common/HardwareBuffer.aidl
index 50306dc..ac95b1c 100644
--- a/graphics/common/aidl/android/hardware/graphics/common/HardwareBuffer.aidl
+++ b/graphics/common/aidl/android/hardware/graphics/common/HardwareBuffer.aidl
@@ -20,11 +20,13 @@
 import android.hardware.graphics.common.HardwareBufferDescription;
 
 /**
- * Stable AIDL counterpart of AHardwareBuffer.
+ * [Deprecated] Stable AIDL counterpart of AHardwareBuffer.
  *
- * @note This is different from the public HardwareBuffer.
- * @sa +ndk libnativewindow#AHardwareBuffer
+ * @note This is different from the public HardwareBuffer. As the public
+         HardwareBuffer now supports being used in stable-aidl interfaces,
+         that is strongly preferred for new usages.
  * @hide
+ * @deprecated: Use instead android.hardware.HardwareBuffer in frameworks/base
  */
 @VintfStability
 parcelable HardwareBuffer {
diff --git a/graphics/composer/aidl/Android.bp b/graphics/composer/aidl/Android.bp
index c105ad4..5699895 100644
--- a/graphics/composer/aidl/Android.bp
+++ b/graphics/composer/aidl/Android.bp
@@ -38,7 +38,7 @@
     ],
     stability: "vintf",
     imports: [
-        "android.hardware.graphics.common-V4",
+        "android.hardware.graphics.common-V5",
         "android.hardware.common-V2",
     ],
     backend: {
@@ -62,14 +62,14 @@
         {
             version: "1",
             imports: [
-                "android.hardware.graphics.common-V4",
+                "android.hardware.graphics.common-V5",
                 "android.hardware.common-V2",
             ],
         },
         {
             version: "2",
             imports: [
-                "android.hardware.graphics.common-V4",
+                "android.hardware.graphics.common-V5",
                 "android.hardware.common-V2",
             ],
         },
diff --git a/graphics/composer/aidl/vts/Android.bp b/graphics/composer/aidl/vts/Android.bp
index e60e1a7..d71999d 100644
--- a/graphics/composer/aidl/vts/Android.bp
+++ b/graphics/composer/aidl/vts/Android.bp
@@ -54,7 +54,6 @@
         "libgui",
         "libhidlbase",
         "libprocessgroup",
-        "libtinyxml2",
         "libvndksupport",
     ],
     header_libs: [
diff --git a/graphics/composer/aidl/vts/ReadbackVts.cpp b/graphics/composer/aidl/vts/ReadbackVts.cpp
index abb58e2..8605628 100644
--- a/graphics/composer/aidl/vts/ReadbackVts.cpp
+++ b/graphics/composer/aidl/vts/ReadbackVts.cpp
@@ -35,6 +35,7 @@
     writer.setLayerPlaneAlpha(mDisplay, mLayer, mAlpha);
     writer.setLayerBlendMode(mDisplay, mLayer, mBlendMode);
     writer.setLayerBrightness(mDisplay, mLayer, mBrightness);
+    writer.setLayerDataspace(mDisplay, mLayer, mDataspace);
 }
 
 std::string ReadbackHelper::getColorModeString(ColorMode mode) {
@@ -99,6 +100,7 @@
 
     layerSettings.geometry.positionTransform = scale * translation;
     layerSettings.whitePointNits = mWhitePointNits;
+    layerSettings.sourceDataspace = static_cast<::android::ui::Dataspace>(mDataspace);
 
     return layerSettings;
 }
@@ -189,6 +191,23 @@
     }
 }
 
+void ReadbackHelper::compareColorBuffers(void* expectedBuffer, void* actualBuffer,
+                                         const uint32_t stride, const uint32_t width,
+                                         const uint32_t height, common::PixelFormat pixelFormat) {
+    const int32_t bytesPerPixel = ReadbackHelper::GetBytesPerPixel(pixelFormat);
+    ASSERT_NE(-1, bytesPerPixel);
+    for (int row = 0; row < height; row++) {
+        for (int col = 0; col < width; col++) {
+            int offset = (row * static_cast<int32_t>(stride) + col) * bytesPerPixel;
+            uint8_t* expectedColor = (uint8_t*)expectedBuffer + offset;
+            uint8_t* actualColor = (uint8_t*)actualBuffer + offset;
+            ASSERT_EQ(expectedColor[0], actualColor[0]);
+            ASSERT_EQ(expectedColor[1], actualColor[1]);
+            ASSERT_EQ(expectedColor[2], actualColor[2]);
+        }
+    }
+}
+
 ReadbackBuffer::ReadbackBuffer(int64_t display, const std::shared_ptr<VtsComposerClient>& client,
                                int32_t width, int32_t height, common::PixelFormat pixelFormat,
                                common::Dataspace dataspace)
@@ -248,6 +267,15 @@
     EXPECT_EQ(::android::OK, status);
 }
 
+::android::sp<::android::GraphicBuffer> ReadbackBuffer::getBuffer() {
+    const auto& [fenceStatus, bufferFence] = mComposerClient->getReadbackBufferFence(mDisplay);
+    EXPECT_TRUE(fenceStatus.isOk());
+    if (bufferFence.get() != -1) {
+        sync_wait(bufferFence.get(), -1);
+    }
+    return mGraphicBuffer;
+}
+
 void TestColorLayer::write(ComposerClientWriter& writer) {
     TestLayer::write(writer);
     writer.setLayerCompositionType(mDisplay, mLayer, Composition::SOLID_COLOR);
@@ -344,10 +372,6 @@
             "TestBufferLayer");
 }
 
-void TestBufferLayer::setDataspace(common::Dataspace dataspace, ComposerClientWriter& writer) {
-    writer.setLayerDataspace(mDisplay, mLayer, dataspace);
-}
-
 void TestBufferLayer::setToClientComposition(ComposerClientWriter& writer) {
     writer.setLayerCompositionType(mDisplay, mLayer, Composition::CLIENT);
 }
diff --git a/graphics/composer/aidl/vts/ReadbackVts.h b/graphics/composer/aidl/vts/ReadbackVts.h
index d5602c1..ee20573 100644
--- a/graphics/composer/aidl/vts/ReadbackVts.h
+++ b/graphics/composer/aidl/vts/ReadbackVts.h
@@ -42,6 +42,9 @@
 static const Color GREEN = {0.0f, 1.0f, 0.0f, 1.0f};
 static const Color BLUE = {0.0f, 0.0f, 1.0f, 1.0f};
 static const Color WHITE = {1.0f, 1.0f, 1.0f, 1.0f};
+static const Color LIGHT_RED = {0.5f, 0.0f, 0.0f, 1.0f};
+static const Color LIGHT_GREEN = {0.0f, 0.5f, 0.0f, 1.0f};
+static const Color LIGHT_BLUE = {0.0f, 0.0f, 0.5f, 1.0f};
 
 class TestRenderEngine;
 
@@ -71,6 +74,8 @@
         mSurfaceDamage = std::move(surfaceDamage);
     }
 
+    void setDataspace(Dataspace dataspace) { mDataspace = dataspace; }
+
     void setTransform(Transform transform) { mTransform = transform; }
     void setAlpha(float alpha) { mAlpha = alpha; }
     void setBlendMode(BlendMode blendMode) { mBlendMode = blendMode; }
@@ -98,6 +103,7 @@
     float mAlpha = 1.0;
     BlendMode mBlendMode = BlendMode::NONE;
     uint32_t mZOrder = 0;
+    Dataspace mDataspace = Dataspace::UNKNOWN;
 };
 
 class TestColorLayer : public TestLayer {
@@ -130,8 +136,6 @@
 
     void setBuffer(std::vector<Color> colors);
 
-    void setDataspace(Dataspace dataspace, ComposerClientWriter& writer);
-
     void setToClientComposition(ComposerClientWriter& writer);
 
     uint32_t getWidth() const { return mWidth; }
@@ -185,6 +189,9 @@
     static void compareColorBuffers(const std::vector<Color>& expectedColors, void* bufferData,
                                     const uint32_t stride, const uint32_t width,
                                     const uint32_t height, PixelFormat pixelFormat);
+    static void compareColorBuffers(void* expectedBuffer, void* actualBuffer, const uint32_t stride,
+                                    const uint32_t width, const uint32_t height,
+                                    PixelFormat pixelFormat);
 };
 
 class ReadbackBuffer {
@@ -196,6 +203,8 @@
 
     void checkReadbackBuffer(const std::vector<Color>& expectedColors);
 
+    ::android::sp<::android::GraphicBuffer> getBuffer();
+
   protected:
     uint32_t mWidth;
     uint32_t mHeight;
diff --git a/graphics/composer/aidl/vts/RenderEngineVts.cpp b/graphics/composer/aidl/vts/RenderEngineVts.cpp
index d1f89d0..4e7f773 100644
--- a/graphics/composer/aidl/vts/RenderEngineVts.cpp
+++ b/graphics/composer/aidl/vts/RenderEngineVts.cpp
@@ -89,4 +89,32 @@
     ASSERT_EQ(::android::OK, mGraphicBuffer->unlock());
 }
 
+void TestRenderEngine::checkColorBuffer(const ::android::sp<::android::GraphicBuffer>& buffer) {
+    ASSERT_EQ(mGraphicBuffer->getWidth(), buffer->getWidth());
+    ASSERT_EQ(mGraphicBuffer->getHeight(), buffer->getHeight());
+    void* renderedBufferData;
+    int32_t bytesPerPixel = -1;
+    int32_t bytesPerStride = -1;
+    ASSERT_EQ(0, mGraphicBuffer->lock(static_cast<uint32_t>(mGraphicBuffer->getUsage()),
+                                      &renderedBufferData, &bytesPerPixel, &bytesPerStride));
+    const uint32_t renderedStride = (bytesPerPixel > 0 && bytesPerStride > 0)
+                                            ? static_cast<uint32_t>(bytesPerStride / bytesPerPixel)
+                                            : mGraphicBuffer->getStride();
+
+    void* bufferData;
+    ASSERT_EQ(0, buffer->lock(static_cast<uint32_t>(buffer->getUsage()), &bufferData,
+                              &bytesPerPixel, &bytesPerStride));
+    const uint32_t bufferStride = (bytesPerPixel > 0 && bytesPerStride > 0)
+                                          ? static_cast<uint32_t>(bytesPerStride / bytesPerPixel)
+                                          : buffer->getStride();
+
+    ASSERT_EQ(renderedStride, bufferStride);
+
+    ReadbackHelper::compareColorBuffers(renderedBufferData, bufferData, bufferStride,
+                                        mGraphicBuffer->getWidth(), mGraphicBuffer->getHeight(),
+                                        mFormat);
+    ASSERT_EQ(::android::OK, buffer->unlock());
+    ASSERT_EQ(::android::OK, mGraphicBuffer->unlock());
+}
+
 }  // namespace aidl::android::hardware::graphics::composer3::vts
diff --git a/graphics/composer/aidl/vts/RenderEngineVts.h b/graphics/composer/aidl/vts/RenderEngineVts.h
index 612f0ea..bbe508f 100644
--- a/graphics/composer/aidl/vts/RenderEngineVts.h
+++ b/graphics/composer/aidl/vts/RenderEngineVts.h
@@ -45,6 +45,7 @@
     };
     void drawLayers();
     void checkColorBuffer(const std::vector<Color>& expectedColors);
+    void checkColorBuffer(const ::android::sp<::android::GraphicBuffer>& buffer);
 
     ::android::renderengine::RenderEngine& getInternalRenderEngine() { return *mRenderEngine; }
 
diff --git a/graphics/composer/aidl/vts/VtsHalGraphicsComposer3_ReadbackTest.cpp b/graphics/composer/aidl/vts/VtsHalGraphicsComposer3_ReadbackTest.cpp
index a83b833..466954f 100644
--- a/graphics/composer/aidl/vts/VtsHalGraphicsComposer3_ReadbackTest.cpp
+++ b/graphics/composer/aidl/vts/VtsHalGraphicsComposer3_ReadbackTest.cpp
@@ -31,12 +31,6 @@
 #include "RenderEngineVts.h"
 #include "VtsComposerClient.h"
 
-// tinyxml2 does implicit conversions >:(
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wconversion"
-#include <tinyxml2.h>
-#pragma clang diagnostic pop
-
 namespace aidl::android::hardware::graphics::composer3::vts {
 namespace {
 
@@ -76,9 +70,9 @@
                                                             ContextPriority::HIGH)
                                 .build())));
 
-        ::android::renderengine::DisplaySettings clientCompositionDisplay;
-        clientCompositionDisplay.physicalDisplay = Rect(getDisplayWidth(), getDisplayHeight());
-        clientCompositionDisplay.clip = clientCompositionDisplay.physicalDisplay;
+        mClientCompositionDisplaySettings.physicalDisplay =
+                Rect(getDisplayWidth(), getDisplayHeight());
+        mClientCompositionDisplaySettings.clip = mClientCompositionDisplaySettings.physicalDisplay;
 
         mTestRenderEngine->initGraphicBuffer(
                 static_cast<uint32_t>(getDisplayWidth()), static_cast<uint32_t>(getDisplayHeight()),
@@ -87,7 +81,7 @@
                         static_cast<uint64_t>(common::BufferUsage::CPU_READ_OFTEN) |
                         static_cast<uint64_t>(common::BufferUsage::CPU_WRITE_OFTEN) |
                         static_cast<uint64_t>(common::BufferUsage::GPU_RENDER_TARGET)));
-        mTestRenderEngine->setDisplaySettings(clientCompositionDisplay);
+        mTestRenderEngine->setDisplaySettings(mClientCompositionDisplaySettings);
     }
 
     void TearDown() override {
@@ -128,63 +122,6 @@
         return {false, graphicBuffer};
     }
 
-    // Gets the per-display XML config
-    std::unique_ptr<tinyxml2::XMLDocument> getDisplayConfigXml(int64_t display) {
-
-        if (auto document = getDisplayConfigXmlByStableId(getStableDisplayId(display));
-                document != nullptr) {
-            return document;
-        }
-
-        // Fallback to looking up a per-port config if no config exists for the full ID
-        if (auto document = getDisplayConfigXmlByPort(getPort(display)); document != nullptr) {
-            return document;
-        }
-
-        return nullptr;
-    }
-
-    // Gets the max display brightness for this display.
-    // If the display config xml does not exist, then assume that the display is not well-configured
-    // enough to provide a display brightness, so return nullopt.
-    std::optional<float> getMaxDisplayBrightnessNits(int64_t display) {
-        const auto document = getDisplayConfigXml(display);
-        if (!document) {
-            // Assume the device doesn't support display brightness
-            return std::nullopt;
-        }
-
-        const auto root = document->RootElement();
-        if (!root) {
-            // If there's somehow no root element, then this isn't a valid config
-            return std::nullopt;
-        }
-
-        const auto screenBrightnessMap = root->FirstChildElement("screenBrightnessMap");
-        if (!screenBrightnessMap) {
-            // A valid display config must have a screen brightness map
-            return std::nullopt;
-        }
-
-        auto point = screenBrightnessMap->FirstChildElement("point");
-        float maxNits = -1.f;
-        while (point != nullptr) {
-            const auto nits = point->FirstChildElement("nits");
-            if (nits) {
-                maxNits = std::max(maxNits, nits->FloatText(-1.f));
-            }
-            point = point->NextSiblingElement("point");
-        }
-
-        if (maxNits < 0.f) {
-            // If we got here, then there were no point elements containing a nit value, so this
-            // config isn't valid
-            return std::nullopt;
-        }
-
-        return maxNits;
-    }
-
     void writeLayers(const std::vector<std::shared_ptr<TestLayer>>& layers) {
         for (const auto& layer : layers) {
             layer->write(*mWriter);
@@ -226,6 +163,7 @@
     std::unique_ptr<TestRenderEngine> mTestRenderEngine;
     common::PixelFormat mPixelFormat;
     common::Dataspace mDataspace;
+    ::android::renderengine::DisplaySettings mClientCompositionDisplaySettings;
 
     static constexpr uint32_t kClientTargetSlotCount = 64;
 
@@ -242,53 +180,6 @@
             }
         }
     }
-
-    uint8_t getPort(int64_t display) {
-        const auto& [status, identification] =
-                mComposerClient->getDisplayIdentificationData(display);
-        EXPECT_TRUE(status.isOk());
-        return static_cast<uint8_t>(identification.port);
-    }
-
-    uint64_t getStableDisplayId(int64_t display) {
-        const auto& [status, identification] =
-                mComposerClient->getDisplayIdentificationData(display);
-        EXPECT_TRUE(status.isOk());
-
-        if (const auto info = ::android::parseDisplayIdentificationData(
-                    static_cast<uint8_t>(identification.port), identification.data)) {
-            return info->id.value;
-        }
-
-        return ::android::PhysicalDisplayId::fromPort(static_cast<uint8_t>(identification.port))
-                .value;
-    }
-
-    std::unique_ptr<tinyxml2::XMLDocument> loadXml(const std::string& path) {
-        auto document = std::make_unique<tinyxml2::XMLDocument>();
-        const tinyxml2::XMLError error = document->LoadFile(path.c_str());
-        if (error != tinyxml2::XML_SUCCESS) {
-            ALOGD("%s: Failed to load config file: %s", __func__, path.c_str());
-            return nullptr;
-        }
-
-        ALOGD("%s: Successfully loaded config file: %s", __func__, path.c_str());
-        return document;
-    }
-
-    std::unique_ptr<tinyxml2::XMLDocument> getDisplayConfigXmlByPort(uint8_t port) {
-        std::stringstream pathBuilder;
-        pathBuilder << "/vendor/etc/displayconfig/display_port_" << static_cast<uint32_t>(port)
-                    << ".xml";
-        return loadXml(pathBuilder.str());
-    }
-
-    std::unique_ptr<tinyxml2::XMLDocument> getDisplayConfigXmlByStableId(uint64_t stableId) {
-        std::stringstream pathBuilder;
-        pathBuilder << "/vendor/etc/displayconfig/display_id_" << stableId
-                    << ".xml";
-       return loadXml(pathBuilder.str());
-    }
 };
 
 class GraphicsCompositionTest : public GraphicsCompositionTestBase,
@@ -381,7 +272,7 @@
                 getDisplayHeight(), common::PixelFormat::RGBA_8888);
         layer->setDisplayFrame({0, 0, getDisplayWidth(), getDisplayHeight()});
         layer->setZOrder(10);
-        layer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode), *mWriter);
+        layer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode));
         ASSERT_NO_FATAL_FAILURE(layer->setBuffer(expectedColors));
 
         std::vector<std::shared_ptr<TestLayer>> layers = {layer};
@@ -565,7 +456,7 @@
                                                        getDisplayHeight(), PixelFormat::RGBA_FP16);
         layer->setDisplayFrame({0, 0, getDisplayWidth(), getDisplayHeight()});
         layer->setZOrder(10);
-        layer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode), *mWriter);
+        layer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode));
 
         std::vector<std::shared_ptr<TestLayer>> layers = {layer};
 
@@ -663,7 +554,7 @@
         deviceLayer->setDisplayFrame({0, 0, static_cast<int32_t>(deviceLayer->getWidth()),
                                       static_cast<int32_t>(deviceLayer->getHeight())});
         deviceLayer->setZOrder(10);
-        deviceLayer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode), *mWriter);
+        deviceLayer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode));
         ASSERT_NO_FATAL_FAILURE(deviceLayer->setBuffer(deviceColors));
         deviceLayer->write(*mWriter);
 
@@ -750,7 +641,7 @@
                                                        getDisplayHeight(), PixelFormat::RGBA_8888);
         layer->setDisplayFrame({0, 0, getDisplayWidth(), getDisplayHeight()});
         layer->setZOrder(10);
-        layer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode), *mWriter);
+        layer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode));
         ASSERT_NO_FATAL_FAILURE(layer->setBuffer(expectedColors));
 
         std::vector<std::shared_ptr<TestLayer>> layers = {layer};
@@ -878,7 +769,7 @@
                                                        getDisplayHeight(), PixelFormat::RGBA_8888);
         layer->setDisplayFrame({0, 0, getDisplayWidth(), getDisplayHeight()});
         layer->setZOrder(10);
-        layer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode), *mWriter);
+        layer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode));
         layer->setSourceCrop({0, static_cast<float>(getDisplayHeight() / 2),
                               static_cast<float>(getDisplayWidth()),
                               static_cast<float>(getDisplayHeight())});
@@ -990,32 +881,6 @@
 }
 
 TEST_P(GraphicsCompositionTest, SetLayerBrightnessDims) {
-    const auto& [status, capabilities] =
-            mComposerClient->getDisplayCapabilities(getPrimaryDisplayId());
-    ASSERT_TRUE(status.isOk());
-
-    const bool brightnessSupport = std::find(capabilities.begin(), capabilities.end(),
-                                             DisplayCapability::BRIGHTNESS) != capabilities.end();
-
-    if (!brightnessSupport) {
-        GTEST_SUCCEED() << "Cannot verify dimming behavior without brightness support";
-        return;
-    }
-
-    const std::optional<float> maxBrightnessNitsOptional =
-            getMaxDisplayBrightnessNits(getPrimaryDisplayId());
-
-    ASSERT_TRUE(maxBrightnessNitsOptional.has_value());
-
-    const float maxBrightnessNits = *maxBrightnessNitsOptional;
-
-    // Preconditions to successfully run are knowing the max brightness and successfully applying
-    // the max brightness
-    ASSERT_GT(maxBrightnessNits, 0.f);
-    mWriter->setDisplayBrightness(getPrimaryDisplayId(), /*brightness*/ 1.f, maxBrightnessNits);
-    execute();
-    ASSERT_TRUE(mReader.takeErrors().empty());
-
     for (ColorMode mode : mTestColorModes) {
         EXPECT_TRUE(mComposerClient
                             ->setColorMode(getPrimaryDisplayId(), mode, RenderIntent::COLORIMETRIC)
@@ -1032,11 +897,14 @@
         const common::Rect redRect = {0, 0, getDisplayWidth(), getDisplayHeight() / 2};
         const common::Rect dimmerRedRect = {0, getDisplayHeight() / 2, getDisplayWidth(),
                                             getDisplayHeight()};
+
+        static constexpr float kMaxBrightnessNits = 300.f;
+
         const auto redLayer =
                 std::make_shared<TestColorLayer>(mComposerClient, getPrimaryDisplayId());
         redLayer->setColor(RED);
         redLayer->setDisplayFrame(redRect);
-        redLayer->setWhitePointNits(maxBrightnessNits);
+        redLayer->setWhitePointNits(kMaxBrightnessNits);
         redLayer->setBrightness(1.f);
 
         const auto dimmerRedLayer =
@@ -1046,7 +914,7 @@
         // Intentionally use a small dimming ratio as some implementations may be more likely to
         // kick into GPU composition to apply dithering when the dimming ratio is high.
         static constexpr float kDimmingRatio = 0.9f;
-        dimmerRedLayer->setWhitePointNits(maxBrightnessNits * kDimmingRatio);
+        dimmerRedLayer->setWhitePointNits(kMaxBrightnessNits * kDimmingRatio);
         dimmerRedLayer->setBrightness(kDimmingRatio);
 
         const std::vector<std::shared_ptr<TestLayer>> layers = {redLayer, dimmerRedLayer};
@@ -1120,7 +988,7 @@
                                                        getDisplayHeight(), PixelFormat::RGBA_8888);
         layer->setDisplayFrame({0, 0, getDisplayWidth(), getDisplayHeight()});
         layer->setZOrder(10);
-        layer->setDataspace(Dataspace::UNKNOWN, *mWriter);
+        layer->setDataspace(Dataspace::UNKNOWN);
         ASSERT_NO_FATAL_FAILURE(layer->setBuffer(topLayerPixelColors));
 
         layer->setBlendMode(blendMode);
@@ -1355,7 +1223,7 @@
                                       getDisplayHeight(), mPixelFormat, mDataspace);
         ASSERT_NO_FATAL_FAILURE(readbackBuffer.setReadbackBuffer());
         mLayer->setTransform(Transform::FLIP_H);
-        mLayer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode), *mWriter);
+        mLayer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode));
 
         std::vector<Color> expectedColors(
                 static_cast<size_t>(getDisplayWidth() * getDisplayHeight()));
@@ -1401,7 +1269,7 @@
         ASSERT_NO_FATAL_FAILURE(readbackBuffer.setReadbackBuffer());
 
         mLayer->setTransform(Transform::FLIP_V);
-        mLayer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode), *mWriter);
+        mLayer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode));
 
         std::vector<Color> expectedColors(
                 static_cast<size_t>(getDisplayWidth() * getDisplayHeight()));
@@ -1446,7 +1314,7 @@
         ASSERT_NO_FATAL_FAILURE(readbackBuffer.setReadbackBuffer());
 
         mLayer->setTransform(Transform::ROT_180);
-        mLayer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode), *mWriter);
+        mLayer->setDataspace(ReadbackHelper::getDataspaceForColorMode(mode));
 
         std::vector<Color> expectedColors(
                 static_cast<size_t>(getDisplayWidth() * getDisplayHeight()));
@@ -1475,6 +1343,100 @@
     }
 }
 
+class GraphicsColorManagementCompositionTest
+    : public GraphicsCompositionTestBase,
+      public testing::WithParamInterface<std::tuple<std::string, Dataspace, Dataspace, Dataspace>> {
+  public:
+    void SetUp() override {
+        SetUpBase(std::get<0>(GetParam()));
+        // for some reason only sRGB reliably works
+        mTestColorModes.erase(
+                std::remove_if(mTestColorModes.begin(), mTestColorModes.end(),
+                               [](ColorMode mode) { return mode != ColorMode::SRGB; }),
+                mTestColorModes.end());
+        auto standard = std::get<1>(GetParam());
+        auto transfer = std::get<2>(GetParam());
+        auto range = std::get<3>(GetParam());
+
+        mLayerDataspace = static_cast<Dataspace>(static_cast<int32_t>(standard) |
+                                                 static_cast<int32_t>(transfer) |
+                                                 static_cast<int32_t>(range));
+        ALOGD("Invoking test for dataspace: {%s, %s, %s}", toString(standard).c_str(),
+              toString(transfer).c_str(), toString(range).c_str());
+    }
+
+    void makeLayer() {
+        mLayer = std::make_shared<TestBufferLayer>(
+                mComposerClient, *mTestRenderEngine, getPrimaryDisplayId(), getDisplayWidth(),
+                getDisplayHeight(), common::PixelFormat::RGBA_8888);
+        mLayer->setDisplayFrame({0, 0, getDisplayWidth(), getDisplayHeight()});
+        mLayer->setZOrder(10);
+        mLayer->setAlpha(1.f);
+        mLayer->setDataspace(mLayerDataspace);
+    }
+
+    void fillColor(Color color) {
+        std::vector<Color> baseColors(static_cast<size_t>(getDisplayWidth() * getDisplayHeight()));
+        ReadbackHelper::fillColorsArea(baseColors, getDisplayWidth(),
+                                       common::Rect{.left = 0,
+                                                    .top = 0,
+                                                    .right = getDisplayWidth(),
+                                                    .bottom = getDisplayHeight()},
+                                       color);
+        ASSERT_NO_FATAL_FAILURE(mLayer->setBuffer(baseColors));
+    }
+
+    Dataspace mLayerDataspace;
+    std::shared_ptr<TestBufferLayer> mLayer;
+};
+
+TEST_P(GraphicsColorManagementCompositionTest, ColorConversion) {
+    for (ColorMode mode : mTestColorModes) {
+        EXPECT_TRUE(mComposerClient
+                            ->setColorMode(getPrimaryDisplayId(), mode, RenderIntent::COLORIMETRIC)
+                            .isOk());
+
+        bool isSupported;
+        ASSERT_NO_FATAL_FAILURE(isSupported = getHasReadbackBuffer());
+        if (!isSupported) {
+            GTEST_SUCCEED() << "Readback not supported or unsupported pixelFormat/dataspace";
+            return;
+        }
+
+        mClientCompositionDisplaySettings.outputDataspace =
+                static_cast<::android::ui::Dataspace>(mDataspace);
+        mTestRenderEngine->setDisplaySettings(mClientCompositionDisplaySettings);
+
+        makeLayer();
+        for (auto color : {LIGHT_RED, LIGHT_GREEN, LIGHT_BLUE}) {
+            ALOGD("Testing color: %f, %f, %f, %f with color mode: %d", color.r, color.g, color.b,
+                  color.a, mode);
+            ReadbackBuffer readbackBuffer(getPrimaryDisplayId(), mComposerClient, getDisplayWidth(),
+                                          getDisplayHeight(), mPixelFormat, mDataspace);
+            ASSERT_NO_FATAL_FAILURE(readbackBuffer.setReadbackBuffer());
+            fillColor(color);
+            writeLayers({mLayer});
+            EXPECT_TRUE(mComposerClient->setPowerMode(getPrimaryDisplayId(), PowerMode::ON).isOk());
+
+            ASSERT_TRUE(mReader.takeErrors().empty());
+            mWriter->validateDisplay(getPrimaryDisplayId(), ComposerClientWriter::kNoTimestamp);
+            execute();
+            if (!mReader.takeChangedCompositionTypes(getPrimaryDisplayId()).empty()) {
+                continue;
+            }
+            ASSERT_TRUE(mReader.takeErrors().empty());
+            mWriter->presentDisplay(getPrimaryDisplayId());
+            execute();
+            ASSERT_TRUE(mReader.takeErrors().empty());
+
+            mTestRenderEngine->setRenderLayers({mLayer});
+            ASSERT_NO_FATAL_FAILURE(mTestRenderEngine->drawLayers());
+            ASSERT_NO_FATAL_FAILURE(
+                    mTestRenderEngine->checkColorBuffer(readbackBuffer.getBuffer()));
+        }
+    }
+}
+
 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(GraphicsCompositionTest);
 INSTANTIATE_TEST_SUITE_P(
         PerInstance, GraphicsCompositionTest,
@@ -1493,5 +1455,17 @@
         testing::ValuesIn(::android::getAidlHalInstanceNames(IComposer::descriptor)),
         ::android::PrintInstanceNameToString);
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(GraphicsColorManagementCompositionTest);
+INSTANTIATE_TEST_SUITE_P(PerInstance, GraphicsColorManagementCompositionTest,
+                         testing::Combine(testing::ValuesIn(::android::getAidlHalInstanceNames(
+                                                  IComposer::descriptor)),
+                                          // Only check sRGB, but verify that extended range
+                                          // doesn't trigger any gamma shifts
+                                          testing::Values(Dataspace::STANDARD_BT709),
+                                          testing::Values(Dataspace::TRANSFER_SRGB),
+                                          // Don't test limited range until we send YUV overlays
+                                          testing::Values(Dataspace::RANGE_FULL,
+                                                          Dataspace::RANGE_EXTENDED)));
+
 }  // namespace
 }  // namespace aidl::android::hardware::graphics::composer3::vts
diff --git a/graphics/mapper/4.0/utils/vts/Android.bp b/graphics/mapper/4.0/utils/vts/Android.bp
index 51e871b..7815d41 100644
--- a/graphics/mapper/4.0/utils/vts/Android.bp
+++ b/graphics/mapper/4.0/utils/vts/Android.bp
@@ -47,7 +47,7 @@
     ],
     export_static_lib_headers: [
         "android.hardware.graphics.allocator@4.0",
-        "android.hardware.graphics.common-V4-ndk",
+        "android.hardware.graphics.common-V5-ndk",
         "android.hardware.graphics.mapper@4.0",
     ],
     export_include_dirs: ["include"],
diff --git a/graphics/mapper/stable-c/implutils/include/android/hardware/graphics/mapper/utils/IMapperProvider.h b/graphics/mapper/stable-c/implutils/include/android/hardware/graphics/mapper/utils/IMapperProvider.h
index 957fdc9..c4d1a0d 100644
--- a/graphics/mapper/stable-c/implutils/include/android/hardware/graphics/mapper/utils/IMapperProvider.h
+++ b/graphics/mapper/stable-c/implutils/include/android/hardware/graphics/mapper/utils/IMapperProvider.h
@@ -106,15 +106,15 @@
     static_assert(std::is_constructible_v<IMPL>, "Implementation must have a no-args constructor");
 
     std::once_flag mLoadOnceFlag;
-    std::optional<IMPL> mImpl;
-    AIMapper mMapper = {};
+    IMPL* _Nullable mImpl;
+    AIMapper* _Nullable mMapper;
 
     static IMPL& impl() {
         return *reinterpret_cast<IMapperProvider<IMPL>*>(provider::sIMapperInstance)->mImpl;
     }
 
     void bindV5() {
-        mMapper.v5 = {
+        mMapper->v5 = {
                 .importBuffer = [](const native_handle_t* _Nonnull handle,
                                    buffer_handle_t _Nullable* _Nonnull outBufferHandle)
                         -> AIMapper_Error { return impl().importBuffer(handle, outBufferHandle); },
@@ -208,13 +208,14 @@
             LOG_ALWAYS_FATAL_IF(provider::sIMapperInstance != nullptr,
                                 "AIMapper implementation already loaded!");
             provider::sIMapperInstance = this;
-            mImpl.emplace();
-            mMapper.version = IMPL::version;
+            mImpl = new IMPL();
+            mMapper = new AIMapper();
+            mMapper->version = IMPL::version;
             if (IMPL::version >= AIMAPPER_VERSION_5) {
                 bindV5();
             }
         });
-        *outImplementation = &mMapper;
+        *outImplementation = mMapper;
         return AIMAPPER_ERROR_NONE;
     }
 };
diff --git a/health/1.0/default/convert.cpp b/health/1.0/default/convert.cpp
index 31b4679..e12e197 100644
--- a/health/1.0/default/convert.cpp
+++ b/health/1.0/default/convert.cpp
@@ -117,7 +117,7 @@
     info.batteryCycleCount      = p->batteryCycleCount;
     info.batteryFullCharge      = p->batteryFullCharge;
     info.batteryChargeCounter   = p->batteryChargeCounter;
-    info.batteryTechnology      = p->batteryTechnology;
+    info.batteryTechnology      = p->batteryTechnology.c_str();
 }
 
 void convertFromHealthInfo(const HealthInfo& info,
diff --git a/health/2.0/vts/OWNERS b/health/2.0/vts/OWNERS
deleted file mode 100644
index 9f96f51..0000000
--- a/health/2.0/vts/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-# Bug component: 30545
-elsk@google.com
-sspatil@google.com
diff --git a/health/2.1/vts/OWNERS b/health/2.1/vts/OWNERS
deleted file mode 100644
index a6803cd..0000000
--- a/health/2.1/vts/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-elsk@google.com
-sspatil@google.com
diff --git a/health/2.1/vts/functional/OWNERS b/health/2.1/vts/functional/OWNERS
deleted file mode 100644
index cd06415..0000000
--- a/health/2.1/vts/functional/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 30545
-elsk@google.com
diff --git a/health/OWNERS b/health/OWNERS
index 0f1bee2..1d4d086 100644
--- a/health/OWNERS
+++ b/health/OWNERS
@@ -1,5 +1,6 @@
 # Bug component: 30545
+
+apelosi@google.com
 elsk@google.com
 smoreland@google.com
 wjack@google.com
-apelosi@google.com
diff --git a/health/storage/1.0/vts/functional/OWNERS b/health/storage/OWNERS
similarity index 79%
rename from health/storage/1.0/vts/functional/OWNERS
rename to health/storage/OWNERS
index 8f66979..7af8d99 100644
--- a/health/storage/1.0/vts/functional/OWNERS
+++ b/health/storage/OWNERS
@@ -1,3 +1,6 @@
 # Bug component: 30545
-elsk@google.com
+
+set noparent
+
 jaegeuk@google.com
+elsk@google.com
diff --git a/health/storage/aidl/vts/functional/OWNERS b/health/storage/aidl/vts/functional/OWNERS
deleted file mode 100644
index a15ed7c..0000000
--- a/health/storage/aidl/vts/functional/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 30545
-file:platform/hardware/interfaces:/health/aidl/OWNERS
\ No newline at end of file
diff --git a/ir/aidl/default/Android.bp b/ir/aidl/default/Android.bp
index a8096c2..4006554 100644
--- a/ir/aidl/default/Android.bp
+++ b/ir/aidl/default/Android.bp
@@ -36,8 +36,58 @@
         "liblog",
         "libutils",
         "android.hardware.ir-V1-ndk",
-        "libhardware"
+        "libhardware",
     ],
 
     srcs: ["main.cpp"],
 }
+
+prebuilt_etc {
+    name: "android.hardware.ir-service.example.rc",
+    src: ":gen-android.hardware.ir-service.example.rc",
+    installable: false,
+}
+
+genrule {
+    name: "gen-android.hardware.ir-service.example.rc",
+    srcs: ["android.hardware.ir-service.example.rc"],
+    out: ["android.hardware.ir-service.example.apex.rc"],
+    cmd: "sed -e 's@/vendor/bin/@/apex/com.android.hardware.ir/bin/@' $(in) > $(out)",
+}
+
+prebuilt_etc {
+    name: "android.hardware.ir-service.example.xml",
+    src: "android.hardware.ir-service.example.xml",
+    sub_dir: "vintf",
+    installable: false,
+}
+
+filegroup {
+    name: "com.android.hardware.ir_file_contexts",
+    srcs: ["apex_file_contexts"],
+}
+
+filegroup {
+    name: "com.android.hardware.ir_apex_manifest.json",
+    srcs: ["apex_manifest.json"],
+}
+
+apex_defaults {
+    name: "com.android.hardware.ir",
+    // Reference to the filegroup instead of direct path since
+    // paths in defaults don't work in a different directory.
+    file_contexts: ":com.android.hardware.ir_file_contexts",
+    manifest: ":com.android.hardware.ir_apex_manifest.json",
+
+    updatable: false,
+    vendor: true,
+
+    binaries: [
+        "android.hardware.ir-service.example",
+    ],
+    prebuilts: [
+        "android.hardware.ir-service.example.rc",
+        "android.hardware.ir-service.example.xml",
+        "android.hardware.consumerir.prebuilt.xml", // feature
+    ],
+}
diff --git a/ir/aidl/default/android.hardware.ir-service.example.rc b/ir/aidl/default/android.hardware.ir-service.example.rc
index d27f282..1a721da 100644
--- a/ir/aidl/default/android.hardware.ir-service.example.rc
+++ b/ir/aidl/default/android.hardware.ir-service.example.rc
@@ -1,4 +1,4 @@
-service vendor.ir-default /vendor/bin/hw/android.hardware.ir-service.example
+service vendor.ir-default /apex/com.android.hardware.ir/bin/hw/android.hardware.ir-service.example
     class hal
     user system
     group system
diff --git a/ir/aidl/default/apex_file_contexts b/ir/aidl/default/apex_file_contexts
new file mode 100644
index 0000000..3bbf131
--- /dev/null
+++ b/ir/aidl/default/apex_file_contexts
@@ -0,0 +1,3 @@
+(/.*)?                                          u:object_r:vendor_file:s0
+/etc(/.*)?                                      u:object_r:vendor_configs_file:s0
+/bin/hw/android\.hardware\.ir-service\.example  u:object_r:hal_ir_default_exec:s0
diff --git a/ir/aidl/default/apex_manifest.json b/ir/aidl/default/apex_manifest.json
new file mode 100644
index 0000000..d384375
--- /dev/null
+++ b/ir/aidl/default/apex_manifest.json
@@ -0,0 +1,4 @@
+{
+    "name": "com.android.hardware.ir",
+    "version": 1
+}
\ No newline at end of file
diff --git a/keymaster/4.0/vts/functional/HmacKeySharingTest.cpp b/keymaster/4.0/vts/functional/HmacKeySharingTest.cpp
index f57a668..1bff076 100644
--- a/keymaster/4.0/vts/functional/HmacKeySharingTest.cpp
+++ b/keymaster/4.0/vts/functional/HmacKeySharingTest.cpp
@@ -137,7 +137,7 @@
     auto nonces = copyNonces(params);
     EXPECT_EQ(allKeymasters().size(), nonces.size());
     std::sort(nonces.begin(), nonces.end());
-    std::unique(nonces.begin(), nonces.end());
+    nonces.erase(std::unique(nonces.begin(), nonces.end()), nonces.end());
     EXPECT_EQ(allKeymasters().size(), nonces.size());
 
     auto responses = computeSharedHmac(allKeymasters(), params);
diff --git a/light/OWNERS b/light/OWNERS
new file mode 100644
index 0000000..d1da8a7
--- /dev/null
+++ b/light/OWNERS
@@ -0,0 +1,5 @@
+# Bug Component: 185877106
+
+michaelwr@google.com
+santoscordon@google.com
+philipjunker@google.com
diff --git a/media/OWNERS b/media/OWNERS
index 71a53ef..01b440a 100644
--- a/media/OWNERS
+++ b/media/OWNERS
@@ -1,7 +1,6 @@
 # Bug component: 25690
 
 # Media team
-jgus@google.com
 lajos@google.com
 taklee@google.com
 wonsik@google.com
diff --git a/media/bufferpool/aidl/Android.bp b/media/bufferpool/aidl/Android.bp
index 8caf525..8e013e0 100644
--- a/media/bufferpool/aidl/Android.bp
+++ b/media/bufferpool/aidl/Android.bp
@@ -46,6 +46,9 @@
             ],
             min_sdk_version: "29",
         },
+        rust: {
+            enabled: true,
+        },
     },
     versions_with_info: [
         {
diff --git a/media/c2/aidl/Android.bp b/media/c2/aidl/Android.bp
index 75d74ac..a153b72 100644
--- a/media/c2/aidl/Android.bp
+++ b/media/c2/aidl/Android.bp
@@ -11,11 +11,12 @@
 
 aidl_interface {
     name: "android.hardware.media.c2",
+    min_sdk_version: "30",
     vendor_available: true,
     double_loadable: true,
     srcs: ["android/hardware/media/c2/*.aidl"],
-    include_dirs: [
-        "frameworks/base/core/java",
+    headers: [
+        "HardwareBuffer_aidl",
     ],
     imports: [
         "android.hardware.common-V2",
@@ -31,6 +32,11 @@
         },
         ndk: {
             enabled: true,
+            apex_available: [
+                "//apex_available:platform",
+                "com.android.media.swcodec",
+                "test_com.android.media.swcodec",
+            ],
             additional_shared_libraries: [
                 "libnativewindow",
             ],
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/BaseBlock.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/BaseBlock.aidl
index 460ff97..069b2cf 100644
--- a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/BaseBlock.aidl
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/BaseBlock.aidl
@@ -35,5 +35,6 @@
 @VintfStability
 union BaseBlock {
   android.hardware.common.NativeHandle nativeBlock;
+  android.hardware.HardwareBuffer hwbBlock;
   android.hardware.media.bufferpool2.BufferStatusMessage pooledBlock;
 }
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IGraphicBufferAllocator.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IGraphicBufferAllocator.aidl
index da3d5ff..3e460dd 100644
--- a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IGraphicBufferAllocator.aidl
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IGraphicBufferAllocator.aidl
@@ -36,7 +36,7 @@
 interface IGraphicBufferAllocator {
   android.hardware.media.c2.IGraphicBufferAllocator.Allocation allocate(in android.hardware.media.c2.IGraphicBufferAllocator.Description desc);
   boolean deallocate(in long id);
-  android.hardware.media.c2.IGraphicBufferAllocator.WaitableFds getWaitableFds();
+  ParcelFileDescriptor getWaitableFd();
   parcelable Allocation {
     android.hardware.HardwareBuffer buffer;
     ParcelFileDescriptor fence;
@@ -47,8 +47,4 @@
     int format;
     long usage;
   }
-  parcelable WaitableFds {
-    ParcelFileDescriptor allocEvent;
-    ParcelFileDescriptor statusEvent;
-  }
 }
diff --git a/media/c2/aidl/android/hardware/media/c2/BaseBlock.aidl b/media/c2/aidl/android/hardware/media/c2/BaseBlock.aidl
index 8b8b8e0..7cc041c 100644
--- a/media/c2/aidl/android/hardware/media/c2/BaseBlock.aidl
+++ b/media/c2/aidl/android/hardware/media/c2/BaseBlock.aidl
@@ -16,6 +16,7 @@
 
 package android.hardware.media.c2;
 
+import android.hardware.HardwareBuffer;
 import android.hardware.common.NativeHandle;
 
 /**
@@ -32,6 +33,10 @@
      */
     NativeHandle nativeBlock;
     /**
+     * #hwbBlock is the opaque representation of a GraphicBuffer
+     */
+    HardwareBuffer hwbBlock;
+    /**
      * #pooledBlock is a reference to a buffer handled by a BufferPool.
      */
     android.hardware.media.bufferpool2.BufferStatusMessage pooledBlock;
diff --git a/media/c2/aidl/android/hardware/media/c2/IGraphicBufferAllocator.aidl b/media/c2/aidl/android/hardware/media/c2/IGraphicBufferAllocator.aidl
index 1c97214..49c4ea4 100644
--- a/media/c2/aidl/android/hardware/media/c2/IGraphicBufferAllocator.aidl
+++ b/media/c2/aidl/android/hardware/media/c2/IGraphicBufferAllocator.aidl
@@ -75,31 +75,22 @@
     boolean deallocate(in long id);
 
     /**
-     * Fds for waitable object events.
-     *
-     * Fds are created by eventfd() with semaphore mode.
-     * For allocEvent, An integer counter regarding dequeuable buffer count is maintained
-     * by client using read()/write() to the fd. The fd can be checked whether it is
-     * readable via poll(). When in readable status, the specified counter is positive
-     * so allocate/dequeue can happen.
-     *
-     * For statusEvent, the client can notify further allocation is not feasible.
-     * e.g.) life-cycle of the underlying allocator is ended.
-     *
-     * C2Fence object should be implemented based on this Fds. Thus, C2Fence can return
-     * either by allocation being ready or allocation being infeasible by the client status
-     * change.
-     */
-    parcelable WaitableFds {
-        ParcelFileDescriptor allocEvent;
-        ParcelFileDescriptor statusEvent;
-    }
-
-    /**
-     * Gets waiable file descriptors.
+     * Gets a waitable file descriptor.
      *
      * Use this method once and cache it in order not to create unnecessary duplicated fds.
-     * The returned array will have two fds.
+     *
+     * Two file descriptors are created by pipe2(), and the reading end will be returned
+     * and shared by this method. Whenever a dequeuable buffer is ready a byte will be
+     * written to the writing end. Whenever a buffer is allocated(or dequeued) a byte will
+     * be read from the reading end.
+     *
+     * The returned file descriptor(the reading end) can be polled whether the read is ready
+     * via ::poll(). If no more allocate() can be fulfilled(by status change or etc.), the
+     * writing end will be closed. In the case, POLLHUP event can be retrieved via ::poll().
+     *
+     * C2Fence object should be implemented based on this Fd. Thus, C2Fence can return
+     * either by allocation being ready or allocation being infeasible by the client status
+     * change.
      *
      * If many waitable objects based on the same fd are competing, all watiable objects will be
      * notified. After being notified, they should invoke allocate(). At least one of them can
@@ -110,5 +101,5 @@
      * @return an fd array which will be wrapped to C2Fence and will be waited for
      *     until allocating is unblocked.
      */
-    WaitableFds getWaitableFds();
+    ParcelFileDescriptor getWaitableFd();
 }
diff --git a/memtrack/aidl/default/Android.bp b/memtrack/aidl/default/Android.bp
index 6c77177..cf95bbb 100644
--- a/memtrack/aidl/default/Android.bp
+++ b/memtrack/aidl/default/Android.bp
@@ -37,3 +37,56 @@
         "Memtrack.cpp",
     ],
 }
+
+cc_binary {
+    name: "android.hardware.memtrack-service.apex",
+    stem: "android.hardware.memtrack-service.example",
+    relative_install_path: "hw",
+    vendor: true,
+
+    stl: "c++_static",
+    static_libs: [
+        "libbase",
+        "android.hardware.memtrack-V1-ndk",
+    ],
+    shared_libs: [
+        "libbinder_ndk",
+        "liblog",
+    ],
+    srcs: [
+        "main.cpp",
+        "Memtrack.cpp",
+    ],
+    installable: false, // installed in APEX
+}
+
+prebuilt_etc {
+    name: "memtrack-default-apex.rc",
+    src: "memtrack-default-apex.rc",
+    installable: false,
+}
+
+prebuilt_etc {
+    name: "memtrack-default.xml",
+    src: "memtrack-default.xml",
+    sub_dir: "vintf",
+    installable: false,
+}
+
+apex {
+    name: "com.android.hardware.memtrack",
+    file_contexts: "apex_file_contexts",
+    manifest: "apex_manifest.json",
+    key: "com.android.hardware.key",
+    certificate: ":com.android.hardware.certificate",
+    updatable: false,
+    vendor: true,
+
+    binaries: [
+        "android.hardware.memtrack-service.apex",
+    ],
+    prebuilts: [
+        "memtrack-default-apex.rc",
+        "memtrack-default.xml",
+    ],
+}
diff --git a/memtrack/aidl/default/apex_file_contexts b/memtrack/aidl/default/apex_file_contexts
new file mode 100644
index 0000000..40c0af4
--- /dev/null
+++ b/memtrack/aidl/default/apex_file_contexts
@@ -0,0 +1,3 @@
+(/.*)?                                                      u:object_r:vendor_file:s0
+/etc(/.*)?                                                  u:object_r:vendor_configs_file:s0
+/bin/hw/android\.hardware\.memtrack-service\.example        u:object_r:hal_memtrack_default_exec:s0
diff --git a/memtrack/aidl/default/apex_manifest.json b/memtrack/aidl/default/apex_manifest.json
new file mode 100644
index 0000000..16d195e
--- /dev/null
+++ b/memtrack/aidl/default/apex_manifest.json
@@ -0,0 +1,4 @@
+{
+    "name": "com.android.hardware.memtrack",
+    "version": 1
+}
\ No newline at end of file
diff --git a/memtrack/aidl/default/memtrack-default-apex.rc b/memtrack/aidl/default/memtrack-default-apex.rc
new file mode 100644
index 0000000..53e712a
--- /dev/null
+++ b/memtrack/aidl/default/memtrack-default-apex.rc
@@ -0,0 +1,4 @@
+service vendor.memtrack-default /apex/com.android.hardware.memtrack/bin/hw/android.hardware.memtrack-service.example
+    class hal
+    user nobody
+    group system
diff --git a/neuralnetworks/aidl/Android.bp b/neuralnetworks/aidl/Android.bp
index be86879..145604c 100644
--- a/neuralnetworks/aidl/Android.bp
+++ b/neuralnetworks/aidl/Android.bp
@@ -17,7 +17,7 @@
     stability: "vintf",
     imports: [
         "android.hardware.common-V2",
-        "android.hardware.graphics.common-V4",
+        "android.hardware.graphics.common-V5",
     ],
     backend: {
         java: {
@@ -40,28 +40,28 @@
             version: "1",
             imports: [
                 "android.hardware.common-V2",
-                "android.hardware.graphics.common-V4",
+                "android.hardware.graphics.common-V5",
             ],
         },
         {
             version: "2",
             imports: [
                 "android.hardware.common-V2",
-                "android.hardware.graphics.common-V4",
+                "android.hardware.graphics.common-V5",
             ],
         },
         {
             version: "3",
             imports: [
                 "android.hardware.common-V2",
-                "android.hardware.graphics.common-V4",
+                "android.hardware.graphics.common-V5",
             ],
         },
         {
             version: "4",
             imports: [
                 "android.hardware.common-V2",
-                "android.hardware.graphics.common-V4",
+                "android.hardware.graphics.common-V5",
             ],
         },
 
diff --git a/oemlock/1.0/vts/functional/OWNERS b/oemlock/1.0/vts/functional/OWNERS
deleted file mode 100644
index ec8c304..0000000
--- a/oemlock/1.0/vts/functional/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-# Bug component: 186411
-chengyouho@google.com
-frankwoo@google.com
diff --git a/authsecret/1.0/vts/functional/OWNERS b/oemlock/OWNERS
similarity index 98%
copy from authsecret/1.0/vts/functional/OWNERS
copy to oemlock/OWNERS
index ec8c304..5a5d074 100644
--- a/authsecret/1.0/vts/functional/OWNERS
+++ b/oemlock/OWNERS
@@ -1,3 +1,4 @@
 # Bug component: 186411
+
 chengyouho@google.com
 frankwoo@google.com
diff --git a/oemlock/aidl/vts/OWNERS b/oemlock/aidl/vts/OWNERS
deleted file mode 100644
index 40d95e4..0000000
--- a/oemlock/aidl/vts/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-chengyouho@google.com
-frankwoo@google.com
diff --git a/power/aidl/aidl_api/android.hardware.power/current/android/hardware/power/Mode.aidl b/power/aidl/aidl_api/android.hardware.power/current/android/hardware/power/Mode.aidl
index efbb300..b8a0710 100644
--- a/power/aidl/aidl_api/android.hardware.power/current/android/hardware/power/Mode.aidl
+++ b/power/aidl/aidl_api/android.hardware.power/current/android/hardware/power/Mode.aidl
@@ -51,4 +51,5 @@
   CAMERA_STREAMING_HIGH,
   GAME,
   GAME_LOADING,
+  DISPLAY_CHANGE,
 }
diff --git a/power/aidl/android/hardware/power/Mode.aidl b/power/aidl/android/hardware/power/Mode.aidl
index cc4b130..78f0363 100644
--- a/power/aidl/android/hardware/power/Mode.aidl
+++ b/power/aidl/android/hardware/power/Mode.aidl
@@ -134,11 +134,6 @@
     DISPLAY_INACTIVE,
 
     /**
-     * Below hints are currently not sent in Android framework but OEM might choose to
-     * implement for power/perf optimizations.
-     */
-
-    /**
      * This mode indicates that low latency audio is active.
      */
     AUDIO_STREAMING_LOW_LATENCY,
@@ -172,4 +167,10 @@
      * This mode indicates that the user is waiting for loading in a game.
      */
     GAME_LOADING,
+
+    /**
+     * This mode indicates that the display layout is changing due to rotation
+     * or switching between inner and outer panels.
+     */
+    DISPLAY_CHANGE,
 }
diff --git a/power/aidl/default/Android.bp b/power/aidl/default/Android.bp
index c0bfbe8..e3af179 100644
--- a/power/aidl/default/Android.bp
+++ b/power/aidl/default/Android.bp
@@ -39,9 +39,11 @@
     ],
 }
 
-filegroup {
+prebuilt_etc {
     name: "android.hardware.power.xml",
-    srcs: ["power-default.xml"],
+    src: "power-default.xml",
+    sub_dir: "vintf",
+    installable: false,
 }
 
 filegroup {
diff --git a/power/aidl/default/apex/Android.bp b/power/aidl/default/apex/Android.bp
index eb04087..a21901f 100644
--- a/power/aidl/default/apex/Android.bp
+++ b/power/aidl/default/apex/Android.bp
@@ -16,17 +16,6 @@
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
-apex_key {
-    name: "com.android.hardware.power.key",
-    public_key: "com.android.hardware.power.avbpubkey",
-    private_key: "com.android.hardware.power.pem",
-}
-
-android_app_certificate {
-    name: "com.android.hardware.power.certificate",
-    certificate: "com.android.hardware.power",
-}
-
 genrule {
     name: "com.android.hardware.power.rc-srcs",
     srcs: [
@@ -34,7 +23,7 @@
         ":android.hardware.power.stats.rc",
     ],
     out: ["com.android.hardware.power.rc"],
-    cmd: "sed -E 's/\\/vendor/\\/apex\\/com.android.hardware.power/' $(in) > $(out)",
+    cmd: "sed -E 's@/vendor/bin/@/apex/com.android.hardware.power/bin/@' $(in) > $(out)",
 }
 
 prebuilt_etc {
@@ -46,13 +35,12 @@
 apex {
     name: "com.android.hardware.power",
     manifest: "apex_manifest.json",
-    key: "com.android.hardware.power.key",
-    certificate: ":com.android.hardware.power.certificate",
+    key: "com.android.hardware.key",
+    certificate: ":com.android.hardware.certificate",
     file_contexts: "file_contexts",
-    use_vndk_as_stable: true,
     updatable: false,
-    // Install the apex in /vendor/apex
-    soc_specific: true,
+    vendor: true,
+
     // Bundle the Power and PowerStats HALs into this one APEX.
     binaries: [
         "android.hardware.power-service.example",
@@ -60,10 +48,8 @@
     ],
     prebuilts: [
         "com.android.hardware.power.rc",
-    ],
-    vintf_fragments: [
-        ":android.hardware.power.xml",
-        ":android.hardware.power.stats.xml",
+        "android.hardware.power.xml",
+        "android.hardware.power.stats.xml",
     ],
     overrides: [
         // Shared lib installed by default but unused by the AIDL implementation.
diff --git a/power/aidl/default/apex/com.android.hardware.power.avbpubkey b/power/aidl/default/apex/com.android.hardware.power.avbpubkey
deleted file mode 100644
index 3b6411d..0000000
--- a/power/aidl/default/apex/com.android.hardware.power.avbpubkey
+++ /dev/null
Binary files differ
diff --git a/power/aidl/default/apex/com.android.hardware.power.pem b/power/aidl/default/apex/com.android.hardware.power.pem
deleted file mode 100644
index d18ae98..0000000
--- a/power/aidl/default/apex/com.android.hardware.power.pem
+++ /dev/null
@@ -1,51 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIIJKQIBAAKCAgEAsUdFjtLq05tWKdQd4aj8V7tmV4KXw41pKGT5Q1CPzrdHF3yJ
-B/8VWdMpjZ+eQO1q8SijPgfvWExeWQVMfxKmwTmj26xWXhIOgo5G02Zva7zOptig
-KGnl/RdFlOiIGC36XeWDhzdIOhlGv+er9Sykf6Ot84OvktTBUTZNJrXQsyYTBRUX
-6B+wloPdBVxVf1HgzjeHUyCy5dTz0xZSWWELoW24tHIvV5FtJVKSY8ZDfuXWLLfT
-he7E93TepjT027U/J/iW4ITJzw4Qq87ick1D/jZDUbTrkqUMFEgPdgCouZ9zt5xG
-pcHAZ/Fcz9DZfEdX9Xy0R5/XbfrJdvDPguJlwK1pZnr/Pe13xxmE+TEohMmaQDqX
-jQNX3UlcfOYUAjnFMGucHDM10KjTMbP8ytCys88aNLiv7FOgVGrQ/djZN8rkMyVP
-ccoksUBMQmjYaQQZ2yZuJMiLD3P6aYkgU5tMEMoMTrBzfcx05GfElal+ZqOFKAzj
-eUxoZTR27wJb684FRbeE45D+y4jpFfrTEXry+aI7GrfDsVDnUqmyObCUttRtaT04
-6kuUmC44wFEg1EBfcWZc1szI192GBjMuZjFcYvJ4vMdCuennqvLNPBDY1PtqzCOf
-D8vpOE3T9rjS23xxFmmSmorwKKQOGChKqO/SaY0axkXgt+FbSsvTBQtZTSsCAwEA
-AQKCAgEArEu3t+MYJcdwS8EDtcF2V5IkGmMrOvziOkdA14Kh8efBKXt49xOc3atU
-VHfQ6AuXh4DWf0BZB7lZbS2wNkSbW2q47ZSmcFEeVxcOkQGawtxDAHfD2ONrirqm
-ft4s/0sYbU/WsIEzKnxMfdEdGHFmA0PCmczfxFYQ+OxMuZW1m5ginirtDEZYa0EH
-e+FMmyypz+K6HDnIhYWd4Aduy718/0zTWlUr2/DUYpTJAD2+dcPNj7Kt2xq/xj2I
-84K+hBa4phF+GgIU3a8u1ryA61RbA+QbM3siBWlxvvh2RlrHoXjuj4JMS2dup9c2
-PCggaCAyxb2IvaAFUbePPJE5LVz6RFT4HnLEydd5Yt+CEAm+iZKfCzyUgFRtb5y0
-HHTME1eVAt/rf/yIXUYA7q8nQ/PtSzIol5KLX4FUjX1MVKNmIWMa+836kxbuYDFB
-K1M1IKc1k0t9Q9F3TRCMhP/6qH/vJfubCGQhSRUMq7JyjivK9GjYST8R07Dpgu9Z
-4i9TRI8d+UVERsg8niCXONVkmNa3U49u2duUvqV3KmKgQ/Hgyy3keDjz6x56ie5w
-e0EusHAsot60W1BvHrdwlmGZjW3JmZEyazUPh9nBUAaQve1rIOpn80kGXx4EAE2o
-HcrcInJx/zVBk1Wk3UQDwmhUNpa64q9+nd9VMaR9SQNK3ah4NDECggEBAOeput2F
-CgRrvzka69i7FbgY4VmpNMIICPIB6gxvwpir/g4/GgYknuBB6ep1ksf/IZfsMp5A
-JTH1KdXqqQm8nV9v+ETYQAO+VnmWKSBKHsNJqONxsKkQ+xIJcusmKBTYLfL88XQg
-YWH3VMXgqPP8DnJYCeVRIKj1WqfEFFHiaLJJB8FgKhtZBwBnibkVG1K0XCkTdUfY
-mME2GRKW/C7DMvuFOpcFVj7Obwn68R2k3zsOhWA5NQGZF5mqhg5KYLVDg3IbMJQQ
-D+DymQxnc2s2ar0q24isy1Y/FOXrA057j1vAN951+pk6F/PCJM/mtAiRjhP0Aru1
-P6bbR11p+wnpU7MCggEBAMPm8Jmwu3F0xsyFC+1sWPAzPiwaMa7/30wANNKKqHVO
-7lUv1WYFbFMyAOzYPp3Y5HxdxNa43reULGk0R20kSu6W6FkApSvAws0rLKRlS5UI
-oZqhLGHUH2M7q07m2RgQY2TJkU2Zq6AH1kjcbSr127ISXKanKpqonwSHy38BTcGt
-Dl2fVioPzK/vwmiNo2njhh95TV4kqlbUfl7xtDt56tbg8oFBwOsK7UGajXYOxTGB
-o1DtO5E+oiOmlclXuo3m4qpSSMv+wM91aRFhHZVIx0vmO8y5lrfU2kM/5DDhJBxV
-FM4TaA+c5tFOTuCLejHc7nM99wVx7O4QZ0wBwETUxKkCggEAH0tBT+1J1iEL+tXV
-KDjVjUHnJyqBUvis5Kw3hqiOO/t33UrO5CeMQrUEuURaqKOhURl6GQCHRcFdfmUt
-ooAVLjA89GfV9et/WPtc4NzCXRUVOGxCNgRyNhSKrpM/9NjjFCDxKQO6w/YaQITB
-rfvNo8qaw5x68ff64BDPweP4yqSs5IVuCrWzCW3zH8pnH3v3uyDCxgrPT8JUDrvQ
-oyyBNZLgwEfbR66xN0Lr0VpVQXALulzf+TBKDNsJMuL/P104Y3Ci1k15J6T94bwT
-zlbSgm1IrKTS7vqkgw6FKtPsILPNmEKNsKc1VxtRx7fdeA7Zh3595Adu6sZSVJ8d
-Z1BamwKCAQAnbu0vgqu4gtEhigaEnDKq5yW0qvElUMwZ+FCpsM+IDYNcEmzaRG0x
-sfcNtdmk3GvhvN5KepwaR/FInAVkqtGKhUXv5Hla/Uo5El/CF8HHFh2xio/sgU5w
-IyqwjzdT6LiZKRnejPhHFkzEDdrLswGuLpQH185zo02fE9aakiCcw8EIh3JItTV2
-lMSFVz11qx7sZvZz5N2E7PEjG3Q0JK5o4o7uBdZXebOYaQvgn8iB1p6RQ6+h5QGu
-O3IbPVWICtnFfxq4NWeKWw/zN6FE04mKdaXD5/e2uVnV/55nWGp0aYvuj2l6+xJb
-P3ARMwI910MIX4jBx9TxdsvUOOYC9PFBAoIBAQDWswLnaNth4pgutngVWbMenSpv
-eK1RA1ldw2NoTZrGlqPB+LvjEMSH/7ioby8YtOyJRIWs3si8HpVF12qneu8qi7b7
-QlUtqyJOTnGalvhrlq5zPhdW+kk2DXvtTylUnz3vSxxi2I7cLhQRryLC/1kAwy67
-wEr0+u59bOvaqe8L1zgtYJpLQZeskUMzdSMIRVDdFShEFrMJU7adUvGpA7OZ6Ogf
-ux2jWr2vv/eKq6fU6kDPi/66MQjPbZPf2Uq6+XedkNkAeELpN4o3hw0/l/rfiK/r
-YUMJBwtjQw/hehtvC4GlgsH1tMZWzCZULo0tcW4qbzyi9PBrWFPteb33OjBc
------END RSA PRIVATE KEY-----
diff --git a/power/aidl/default/apex/com.android.hardware.power.pk8 b/power/aidl/default/apex/com.android.hardware.power.pk8
deleted file mode 100644
index e45435d..0000000
--- a/power/aidl/default/apex/com.android.hardware.power.pk8
+++ /dev/null
Binary files differ
diff --git a/power/aidl/default/apex/com.android.hardware.power.x509.pem b/power/aidl/default/apex/com.android.hardware.power.x509.pem
deleted file mode 100644
index 9f0c5f0..0000000
--- a/power/aidl/default/apex/com.android.hardware.power.x509.pem
+++ /dev/null
@@ -1,34 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIF2TCCA8ECFDFsXbm5CdS/UtQZgTiF8Umr8LrLMA0GCSqGSIb3DQEBCwUAMIGn
-MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91
-bnRhaW4gVmlldzEQMA4GA1UECgwHQW5kcm9pZDEQMA4GA1UECwwHQW5kcm9pZDEi
-MCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTEjMCEGA1UEAwwaY29t
-LmFuZHJvaWQuaGFyZHdhcmUucG93ZXIwIBcNMjExMDIwMTcwNTA0WhgPNDc1OTA5
-MTYxNzA1MDRaMIGnMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEW
-MBQGA1UEBwwNTW91bnRhaW4gVmlldzEQMA4GA1UECgwHQW5kcm9pZDEQMA4GA1UE
-CwwHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTEj
-MCEGA1UEAwwaY29tLmFuZHJvaWQuaGFyZHdhcmUucG93ZXIwggIiMA0GCSqGSIb3
-DQEBAQUAA4ICDwAwggIKAoICAQC/37fhOkOfgM2e+M7bMJ1baLFif8dKGwRa6mkJ
-9HWmuOgRcTKllzuEHtrJ0jzur3cDy6/0oZSfA/E1ck3DdRHMQadW26JSNSg6fCU9
-h1kDzkakZgyr3DsJnKGoSHCJ2V2kVbCnd6GuOaOU1ZZISw1I+BWJDc3t1mZPs80D
-ar7/hoIZnsWRoE/eWgJDcWWscRsquSi+q6hyqlCbRvwRznPaDGwmb4geHNugCXkz
-EtCswfc5jiT8DjMDkgVsGO/WcYj2GWT0K0H+Zf1CmEO9fAoXTLfVBjdumtGILgii
-d/TJe2tOBSWyZz6sVzfac2PvUH5Lm8TNUXuLV5IEdcpySge0vqYQwAyd2EgsTH1e
-mRNSk9NerpmfCFEySRRP3BWMGRhbST1d8M3v9Bq0QFhrxoAF12r6GXBUpp9XcOL5
-pBTcAkA9XI++mfz4pDzyGRGOy4WX+8XtsaVZ/14JklupSLr0Tt7oaNocUhoXB03g
-4B0jUTX0hNnVzCxzJypw6YJ60Zc8z+z8pEF34FWarHec1QbkFuyWxbaTPQ4d2NLH
-8zDxQpMILErWdAgKsRL0d8RFG5fBcleEoBM2kKHMAgnP+1qyDqBgt8zloWbmmblw
-JXMuoePFOgeVcgPrZ3EGJSx+s4+dQGQc6r/GwKLKSWpUvHxTIGug76IX9xmptB+I
-F3xb2QIDAQABMA0GCSqGSIb3DQEBCwUAA4ICAQANISf3Vi2eueOlzzfnEGGa+CXz
-nvlgUXKv8Gv0/Pbg5uC1BaHTAUgRu5rvrfP9p3Mdj86I/HbE/F4Vkuzqb8/JTWGA
-mG636zAsJRJr0fnkbPma9wVEPSK8MF1QqM6PmKXboixX82TqV1R1sRYG+9hh9W3u
-isDzYDb2ODE0X9M8/3hLS28zdCdtl4zCRK6KB86aGxvkVEj4qDA5l+AbVYevS/SU
-hz1+K/aM0Fi6MZovo5kd/Mof5l05e1TEgCoL1FtFX79r+PYGHJ8/LjtEMkFgwqvG
-CLx2sOV09EHZU27EbVvSs1JYMMXgeAvKaHsVZ51QlSzW4esg/E6z4pw654p8qyK/
-WLXIZ7BMILl1sHYmGqXitnu19puvNks2/+hyqVr0seM5GyQDuwBE8nx6xZzTRxdj
-4TZyN9LuMc9/cKJFvOPqD152bkA2frCLEzYCQreDWwxsWcUHzYrQT+v2SqzP6Ue2
-Xn06HDLx9wBL7Dz6no05SlNS0u1KdvKas6FKZHO+QaKKsBlDmXbMrBTcuUI6OXv2
-6NpVbeyDd0+A23hDiNSgI6zTY6jMidesNExB7rW/bCE4ltPyxFAB+sffyXounODc
-groB5CaS2bv+H1IXJzMMe4LkgQPl1C7G+I3KvJmnrYwmIhLIDuxP82arClIDzccS
-ExRR7ugEg91XCc87Zg==
------END CERTIFICATE-----
diff --git a/power/aidl/default/apex/file_contexts b/power/aidl/default/apex/file_contexts
index 3433851..3b7526a 100644
--- a/power/aidl/default/apex/file_contexts
+++ b/power/aidl/default/apex/file_contexts
@@ -1,3 +1,4 @@
 (/.*)?                                                      u:object_r:vendor_file:s0
+/etc(/.*)?                                                  u:object_r:vendor_configs_file:s0
 /bin/hw/android\.hardware\.power-service\.example           u:object_r:hal_power_default_exec:s0
 /bin/hw/android\.hardware\.power\.stats-service\.example    u:object_r:hal_power_stats_default_exec:s0
diff --git a/power/stats/aidl/default/Android.bp b/power/stats/aidl/default/Android.bp
index d3ab29b..cc0fbf6 100644
--- a/power/stats/aidl/default/Android.bp
+++ b/power/stats/aidl/default/Android.bp
@@ -38,9 +38,11 @@
     ],
 }
 
-filegroup {
+prebuilt_etc {
     name: "android.hardware.power.stats.xml",
-    srcs: ["power.stats-default.xml"],
+    src: "power.stats-default.xml",
+    sub_dir: "vintf",
+    installable: false,
 }
 
 filegroup {
diff --git a/radio/1.0/vts/functional/OWNERS b/radio/1.0/vts/functional/OWNERS
deleted file mode 100644
index 1b6d937..0000000
--- a/radio/1.0/vts/functional/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 20868
-shuoq@google.com
diff --git a/radio/1.1/vts/OWNERS b/radio/1.1/vts/OWNERS
deleted file mode 100644
index 4d199ca..0000000
--- a/radio/1.1/vts/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 20868
-include ../../1.0/vts/OWNERS
diff --git a/radio/1.2/vts/OWNERS b/radio/1.2/vts/OWNERS
deleted file mode 100644
index 4d199ca..0000000
--- a/radio/1.2/vts/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 20868
-include ../../1.0/vts/OWNERS
diff --git a/radio/1.3/vts/OWNERS b/radio/1.3/vts/OWNERS
deleted file mode 100644
index 4d199ca..0000000
--- a/radio/1.3/vts/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 20868
-include ../../1.0/vts/OWNERS
diff --git a/radio/1.4/vts/OWNERS b/radio/1.4/vts/OWNERS
deleted file mode 100644
index 4d199ca..0000000
--- a/radio/1.4/vts/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 20868
-include ../../1.0/vts/OWNERS
diff --git a/radio/1.5/vts/OWNERS b/radio/1.5/vts/OWNERS
deleted file mode 100644
index 4d199ca..0000000
--- a/radio/1.5/vts/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 20868
-include ../../1.0/vts/OWNERS
diff --git a/radio/1.6/vts/OWNERS b/radio/1.6/vts/OWNERS
deleted file mode 100644
index a07c917..0000000
--- a/radio/1.6/vts/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-include ../../1.0/vts/OWNERS
diff --git a/radio/1.0/vts/OWNERS b/radio/OWNERS
similarity index 63%
rename from radio/1.0/vts/OWNERS
rename to radio/OWNERS
index 117692a..67ac2e2 100644
--- a/radio/1.0/vts/OWNERS
+++ b/radio/OWNERS
@@ -1,5 +1,4 @@
 # Bug component: 20868
-jminjie@google.com
-sarahchin@google.com
-shuoq@google.com
+
 jackyu@google.com
+sarahchin@google.com
diff --git a/radio/aidl/OWNERS b/radio/aidl/OWNERS
deleted file mode 100644
index 7b01aad..0000000
--- a/radio/aidl/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-# Bug component: 20868
-include ../1.0/vts/OWNERS
-
diff --git a/radio/aidl/android/hardware/radio/network/IRadioNetwork.aidl b/radio/aidl/android/hardware/radio/network/IRadioNetwork.aidl
index e4c3856..878ad23 100644
--- a/radio/aidl/android/hardware/radio/network/IRadioNetwork.aidl
+++ b/radio/aidl/android/hardware/radio/network/IRadioNetwork.aidl
@@ -32,6 +32,7 @@
 
 /**
  * This interface is used by telephony and telecom to talk to cellular radio for network APIs.
+ * All functions apply to both terrestrial and extraterrestrial (satellite) based cellular networks.
  * All the functions have minimum one parameter:
  * serial: which corresponds to serial no. of request. Serial numbers must only be memorized for the
  * duration of a method call. If clients provide colliding serials (including passing the same
diff --git a/radio/aidl/compat/OWNERS b/radio/aidl/compat/OWNERS
index 471d806..3a7a009 100644
--- a/radio/aidl/compat/OWNERS
+++ b/radio/aidl/compat/OWNERS
@@ -1,3 +1,3 @@
 # Bug component: 20868
-include ../../1.0/vts/OWNERS
+
 twasilczyk@google.com
diff --git a/radio/aidl/vts/radio_data_test.cpp b/radio/aidl/vts/radio_data_test.cpp
index 0fb2fb4..f31c254 100644
--- a/radio/aidl/vts/radio_data_test.cpp
+++ b/radio/aidl/vts/radio_data_test.cpp
@@ -214,7 +214,8 @@
         ASSERT_TRUE(CheckAnyOfErrors(radioRsp_data->rspInfo.error,
                                      {RadioError::NONE, RadioError::RADIO_NOT_AVAILABLE,
                                       RadioError::OP_NOT_ALLOWED_BEFORE_REG_TO_NW}));
-        if (radioRsp_data->setupDataCallResult.trafficDescriptors.size() <= 0) {
+        if (radioRsp_data->setupDataCallResult.trafficDescriptors.size() <= 0 ||
+            !radioRsp_data->setupDataCallResult.trafficDescriptors[0].osAppId.has_value()) {
             return;
         }
         EXPECT_EQ(trafficDescriptor.osAppId.value().osAppId,
diff --git a/radio/aidl/vts/radio_network_test.cpp b/radio/aidl/vts/radio_network_test.cpp
index 253ef82..6643c1e 100644
--- a/radio/aidl/vts/radio_network_test.cpp
+++ b/radio/aidl/vts/radio_network_test.cpp
@@ -23,6 +23,19 @@
 
 #define ASSERT_OK(ret) ASSERT_TRUE(ret.isOk())
 
+namespace {
+const RadioAccessSpecifierBands EUTRAN_BAND_17 =
+        RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::eutranBands>(
+                {EutranBands::BAND_17});
+const RadioAccessSpecifierBands EUTRAN_BAND_20 =
+        RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::eutranBands>(
+                {EutranBands::BAND_20});
+const RadioAccessSpecifier EUTRAN_SPECIFIER_17 = {
+        .accessNetwork = AccessNetwork::EUTRAN, .bands = EUTRAN_BAND_17, .channels = {1, 2}};
+const RadioAccessSpecifier EUTRAN_SPECIFIER_20 = {
+        .accessNetwork = AccessNetwork::EUTRAN, .bands = EUTRAN_BAND_20, .channels = {128, 129}};
+}  // namespace
+
 void RadioNetworkTest::SetUp() {
     RadioServiceTest::SetUp();
     std::string serviceName = GetParam();
@@ -289,7 +302,7 @@
     signalThresholdInfo.hysteresisDb = 10;  // hysteresisDb too large given threshold list deltas
     signalThresholdInfo.thresholds = {-109, -103, -97, -89};
     signalThresholdInfo.isEnabled = true;
-    signalThresholdInfo.ran = AccessNetwork::GERAN;
+    signalThresholdInfo.ran = AccessNetwork::EUTRAN;
 
     ndk::ScopedAStatus res =
             radio_network->setSignalStrengthReportingCriteria(serial, {signalThresholdInfo});
@@ -314,7 +327,7 @@
     signalThresholdInfo.hysteresisMs = 0;
     signalThresholdInfo.hysteresisDb = 0;
     signalThresholdInfo.isEnabled = true;
-    signalThresholdInfo.ran = AccessNetwork::GERAN;
+    signalThresholdInfo.ran = AccessNetwork::EUTRAN;
 
     ndk::ScopedAStatus res =
             radio_network->setSignalStrengthReportingCriteria(serial, {signalThresholdInfo});
@@ -351,7 +364,8 @@
 
     ALOGI("setSignalStrengthReportingCriteria_Geran, rspInfo.error = %s\n",
           toString(radioRsp_network->rspInfo.error).c_str());
-    ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error, {RadioError::NONE}));
+    ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
+                                 {RadioError::NONE, RadioError::REQUEST_NOT_SUPPORTED}));
 }
 
 /*
@@ -677,7 +691,7 @@
         ASSERT_OK(res);
         EXPECT_EQ(std::cv_status::no_timeout, wait());
         if (radioRsp_network->rspInfo.error == RadioError::NONE) {
-            supportedSignalThresholdInfos.push_back(signalThresholdInfoGeran);
+            supportedSignalThresholdInfos.push_back(signalThresholdInfoEutran);
         } else {
             // Refer to IRadioNetworkResponse#setSignalStrengthReportingCriteriaResponse
             ASSERT_TRUE(CheckAnyOfErrors(
@@ -711,7 +725,7 @@
     ndk::ScopedAStatus res = radio_network->setLinkCapacityReportingCriteria(
             serial, 5000,
             5000,  // hysteresisDlKbps too big for thresholds delta
-            100, {1000, 5000, 10000, 20000}, {500, 1000, 5000, 10000}, AccessNetwork::GERAN);
+            100, {1000, 5000, 10000, 20000}, {500, 1000, 5000, 10000}, AccessNetwork::EUTRAN);
     ASSERT_OK(res);
     EXPECT_EQ(std::cv_status::no_timeout, wait());
     EXPECT_EQ(RadioResponseType::SOLICITED, radioRsp_network->rspInfo.type);
@@ -719,11 +733,7 @@
 
     ALOGI("setLinkCapacityReportingCriteria_invalidHysteresisDlKbps, rspInfo.error = %s\n",
           toString(radioRsp_network->rspInfo.error).c_str());
-    // Allow REQUEST_NOT_SUPPORTED as setLinkCapacityReportingCriteria() may not be supported
-    // for GERAN
-    ASSERT_TRUE(
-            CheckAnyOfErrors(radioRsp_network->rspInfo.error,
-                             {RadioError::INVALID_ARGUMENTS, RadioError::REQUEST_NOT_SUPPORTED}));
+    ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error, {RadioError::INVALID_ARGUMENTS}));
 }
 
 /*
@@ -734,7 +744,7 @@
 
     ndk::ScopedAStatus res = radio_network->setLinkCapacityReportingCriteria(
             serial, 5000, 500, 1000,  // hysteresisUlKbps too big for thresholds delta
-            {1000, 5000, 10000, 20000}, {500, 1000, 5000, 10000}, AccessNetwork::GERAN);
+            {1000, 5000, 10000, 20000}, {500, 1000, 5000, 10000}, AccessNetwork::EUTRAN);
     ASSERT_OK(res);
     EXPECT_EQ(std::cv_status::no_timeout, wait());
     EXPECT_EQ(RadioResponseType::SOLICITED, radioRsp_network->rspInfo.type);
@@ -742,11 +752,7 @@
 
     ALOGI("setLinkCapacityReportingCriteria_invalidHysteresisUlKbps, rspInfo.error = %s\n",
           toString(radioRsp_network->rspInfo.error).c_str());
-    // Allow REQUEST_NOT_SUPPORTED as setLinkCapacityReportingCriteria() may not be supported
-    // for GERAN
-    ASSERT_TRUE(
-            CheckAnyOfErrors(radioRsp_network->rspInfo.error,
-                             {RadioError::INVALID_ARGUMENTS, RadioError::REQUEST_NOT_SUPPORTED}));
+    ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error, {RadioError::INVALID_ARGUMENTS}));
 }
 
 /*
@@ -756,7 +762,7 @@
     serial = GetRandomSerialNumber();
 
     ndk::ScopedAStatus res = radio_network->setLinkCapacityReportingCriteria(
-            serial, 0, 0, 0, {}, {}, AccessNetwork::GERAN);
+            serial, 0, 0, 0, {}, {}, AccessNetwork::EUTRAN);
     ASSERT_OK(res);
     EXPECT_EQ(std::cv_status::no_timeout, wait());
     EXPECT_EQ(RadioResponseType::SOLICITED, radioRsp_network->rspInfo.type);
@@ -764,10 +770,7 @@
 
     ALOGI("setLinkCapacityReportingCriteria_emptyParams, rspInfo.error = %s\n",
           toString(radioRsp_network->rspInfo.error).c_str());
-    // Allow REQUEST_NOT_SUPPORTED as setLinkCapacityReportingCriteria() may not be supported
-    // for GERAN
-    ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
-                                 {RadioError::NONE, RadioError::REQUEST_NOT_SUPPORTED}));
+    ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error, {RadioError::NONE}));
 }
 
 /*
@@ -808,19 +811,9 @@
     }
     std::vector<RadioAccessSpecifier> originalSpecifiers = radioRsp_network->specifiers;
 
-    RadioAccessSpecifierBands bandP900 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_P900});
-    RadioAccessSpecifierBands band850 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_850});
-    RadioAccessSpecifier specifierP900 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = bandP900, .channels = {1, 2}};
-    RadioAccessSpecifier specifier850 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = band850, .channels = {128, 129}};
-
     serial = GetRandomSerialNumber();
-    res = radio_network->setSystemSelectionChannels(serial, true, {specifierP900, specifier850});
+    res = radio_network->setSystemSelectionChannels(serial, true,
+                                                    {::EUTRAN_SPECIFIER_17, ::EUTRAN_SPECIFIER_20});
     ASSERT_OK(res);
     EXPECT_EQ(std::cv_status::no_timeout, wait());
     EXPECT_EQ(RadioResponseType::SOLICITED, radioRsp_network->rspInfo.type);
@@ -833,8 +826,8 @@
 
     if (radioRsp_network->rspInfo.error == RadioError::NONE) {
         serial = GetRandomSerialNumber();
-        res = radio_network->setSystemSelectionChannels(serial, false,
-                                                        {specifierP900, specifier850});
+        res = radio_network->setSystemSelectionChannels(
+                serial, false, {::EUTRAN_SPECIFIER_17, ::EUTRAN_SPECIFIER_20});
         ASSERT_OK(res);
         EXPECT_EQ(std::cv_status::no_timeout, wait());
         EXPECT_EQ(RadioResponseType::SOLICITED, radioRsp_network->rspInfo.type);
@@ -857,20 +850,9 @@
 TEST_P(RadioNetworkTest, startNetworkScan) {
     serial = GetRandomSerialNumber();
 
-    RadioAccessSpecifierBands band17 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::eutranBands>(
-                    {EutranBands::BAND_17});
-    RadioAccessSpecifierBands band20 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::eutranBands>(
-                    {EutranBands::BAND_20});
-    RadioAccessSpecifier specifier17 = {
-            .accessNetwork = AccessNetwork::EUTRAN, .bands = band17, .channels = {1, 2}};
-    RadioAccessSpecifier specifier20 = {
-            .accessNetwork = AccessNetwork::EUTRAN, .bands = band20, .channels = {128, 129}};
-
     NetworkScanRequest request = {.type = NetworkScanRequest::SCAN_TYPE_ONE_SHOT,
                                   .interval = 60,
-                                  .specifiers = {specifier17, specifier20},
+                                  .specifiers = {::EUTRAN_SPECIFIER_17, ::EUTRAN_SPECIFIER_20},
                                   .maxSearchTime = 60,
                                   .incrementalResults = false,
                                   .incrementalResultsPeriodicity = 1};
@@ -892,10 +874,9 @@
             ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
                                          {RadioError::NONE, RadioError::OPERATION_NOT_ALLOWED}));
         } else {
-            ASSERT_TRUE(CheckAnyOfErrors(
-                    radioRsp_network->rspInfo.error,
-                    {RadioError::NONE, RadioError::OPERATION_NOT_ALLOWED, RadioError::NONE,
-                     RadioError::INVALID_ARGUMENTS, RadioError::REQUEST_NOT_SUPPORTED}));
+            ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
+                                         {RadioError::NONE, RadioError::OPERATION_NOT_ALLOWED,
+                                          RadioError::INVALID_ARGUMENTS}));
         }
     }
 
@@ -925,9 +906,8 @@
         ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
                                      {RadioError::SIM_ABSENT, RadioError::INVALID_ARGUMENTS}));
     } else if (cardStatus.cardState == CardStatus::STATE_PRESENT) {
-        ASSERT_TRUE(CheckAnyOfErrors(
-                radioRsp_network->rspInfo.error,
-                {RadioError::INVALID_ARGUMENTS, RadioError::REQUEST_NOT_SUPPORTED}));
+        ASSERT_TRUE(
+                CheckAnyOfErrors(radioRsp_network->rspInfo.error, {RadioError::INVALID_ARGUMENTS}));
     }
 }
 
@@ -937,20 +917,9 @@
 TEST_P(RadioNetworkTest, startNetworkScan_InvalidInterval1) {
     serial = GetRandomSerialNumber();
 
-    RadioAccessSpecifierBands bandP900 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_P900});
-    RadioAccessSpecifierBands band850 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_850});
-    RadioAccessSpecifier specifierP900 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = bandP900, .channels = {1, 2}};
-    RadioAccessSpecifier specifier850 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = band850, .channels = {128, 129}};
-
     NetworkScanRequest request = {.type = NetworkScanRequest::SCAN_TYPE_PERIODIC,
                                   .interval = 4,
-                                  .specifiers = {specifierP900, specifier850},
+                                  .specifiers = {::EUTRAN_SPECIFIER_17, ::EUTRAN_SPECIFIER_20},
                                   .maxSearchTime = 60,
                                   .incrementalResults = false,
                                   .incrementalResultsPeriodicity = 1};
@@ -966,9 +935,8 @@
         ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
                                      {RadioError::SIM_ABSENT, RadioError::INVALID_ARGUMENTS}));
     } else if (cardStatus.cardState == CardStatus::STATE_PRESENT) {
-        ASSERT_TRUE(CheckAnyOfErrors(
-                radioRsp_network->rspInfo.error,
-                {RadioError::INVALID_ARGUMENTS, RadioError::REQUEST_NOT_SUPPORTED}));
+        ASSERT_TRUE(
+                CheckAnyOfErrors(radioRsp_network->rspInfo.error, {RadioError::INVALID_ARGUMENTS}));
     }
 }
 
@@ -978,20 +946,9 @@
 TEST_P(RadioNetworkTest, startNetworkScan_InvalidInterval2) {
     serial = GetRandomSerialNumber();
 
-    RadioAccessSpecifierBands bandP900 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_P900});
-    RadioAccessSpecifierBands band850 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_850});
-    RadioAccessSpecifier specifierP900 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = bandP900, .channels = {1, 2}};
-    RadioAccessSpecifier specifier850 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = band850, .channels = {128, 129}};
-
     NetworkScanRequest request = {.type = NetworkScanRequest::SCAN_TYPE_PERIODIC,
                                   .interval = 301,
-                                  .specifiers = {specifierP900, specifier850},
+                                  .specifiers = {::EUTRAN_SPECIFIER_17, ::EUTRAN_SPECIFIER_20},
                                   .maxSearchTime = 60,
                                   .incrementalResults = false,
                                   .incrementalResultsPeriodicity = 1};
@@ -1007,9 +964,8 @@
         ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
                                      {RadioError::SIM_ABSENT, RadioError::INVALID_ARGUMENTS}));
     } else if (cardStatus.cardState == CardStatus::STATE_PRESENT) {
-        ASSERT_TRUE(CheckAnyOfErrors(
-                radioRsp_network->rspInfo.error,
-                {RadioError::INVALID_ARGUMENTS, RadioError::REQUEST_NOT_SUPPORTED}));
+        ASSERT_TRUE(
+                CheckAnyOfErrors(radioRsp_network->rspInfo.error, {RadioError::INVALID_ARGUMENTS}));
     }
 }
 
@@ -1019,20 +975,9 @@
 TEST_P(RadioNetworkTest, startNetworkScan_InvalidMaxSearchTime1) {
     serial = GetRandomSerialNumber();
 
-    RadioAccessSpecifierBands bandP900 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_P900});
-    RadioAccessSpecifierBands band850 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_850});
-    RadioAccessSpecifier specifierP900 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = bandP900, .channels = {1, 2}};
-    RadioAccessSpecifier specifier850 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = band850, .channels = {128, 129}};
-
     NetworkScanRequest request = {.type = NetworkScanRequest::SCAN_TYPE_ONE_SHOT,
                                   .interval = 60,
-                                  .specifiers = {specifierP900, specifier850},
+                                  .specifiers = {::EUTRAN_SPECIFIER_17, ::EUTRAN_SPECIFIER_20},
                                   .maxSearchTime = 59,
                                   .incrementalResults = false,
                                   .incrementalResultsPeriodicity = 1};
@@ -1048,9 +993,8 @@
         ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
                                      {RadioError::SIM_ABSENT, RadioError::INVALID_ARGUMENTS}));
     } else if (cardStatus.cardState == CardStatus::STATE_PRESENT) {
-        ASSERT_TRUE(CheckAnyOfErrors(
-                radioRsp_network->rspInfo.error,
-                {RadioError::INVALID_ARGUMENTS, RadioError::REQUEST_NOT_SUPPORTED}));
+        ASSERT_TRUE(
+                CheckAnyOfErrors(radioRsp_network->rspInfo.error, {RadioError::INVALID_ARGUMENTS}));
     }
 }
 
@@ -1060,20 +1004,9 @@
 TEST_P(RadioNetworkTest, startNetworkScan_InvalidMaxSearchTime2) {
     serial = GetRandomSerialNumber();
 
-    RadioAccessSpecifierBands bandP900 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_P900});
-    RadioAccessSpecifierBands band850 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_850});
-    RadioAccessSpecifier specifierP900 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = bandP900, .channels = {1, 2}};
-    RadioAccessSpecifier specifier850 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = band850, .channels = {128, 129}};
-
     NetworkScanRequest request = {.type = NetworkScanRequest::SCAN_TYPE_ONE_SHOT,
                                   .interval = 60,
-                                  .specifiers = {specifierP900, specifier850},
+                                  .specifiers = {::EUTRAN_SPECIFIER_17, ::EUTRAN_SPECIFIER_20},
                                   .maxSearchTime = 3601,
                                   .incrementalResults = false,
                                   .incrementalResultsPeriodicity = 1};
@@ -1089,9 +1022,8 @@
         ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
                                      {RadioError::SIM_ABSENT, RadioError::INVALID_ARGUMENTS}));
     } else if (cardStatus.cardState == CardStatus::STATE_PRESENT) {
-        ASSERT_TRUE(CheckAnyOfErrors(
-                radioRsp_network->rspInfo.error,
-                {RadioError::INVALID_ARGUMENTS, RadioError::REQUEST_NOT_SUPPORTED}));
+        ASSERT_TRUE(
+                CheckAnyOfErrors(radioRsp_network->rspInfo.error, {RadioError::INVALID_ARGUMENTS}));
     }
 }
 
@@ -1101,20 +1033,9 @@
 TEST_P(RadioNetworkTest, startNetworkScan_InvalidPeriodicity1) {
     serial = GetRandomSerialNumber();
 
-    RadioAccessSpecifierBands bandP900 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_P900});
-    RadioAccessSpecifierBands band850 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_850});
-    RadioAccessSpecifier specifierP900 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = bandP900, .channels = {1, 2}};
-    RadioAccessSpecifier specifier850 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = band850, .channels = {128, 129}};
-
     NetworkScanRequest request = {.type = NetworkScanRequest::SCAN_TYPE_ONE_SHOT,
                                   .interval = 60,
-                                  .specifiers = {specifierP900, specifier850},
+                                  .specifiers = {::EUTRAN_SPECIFIER_17, ::EUTRAN_SPECIFIER_20},
                                   .maxSearchTime = 600,
                                   .incrementalResults = true,
                                   .incrementalResultsPeriodicity = 0};
@@ -1130,9 +1051,8 @@
         ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
                                      {RadioError::SIM_ABSENT, RadioError::INVALID_ARGUMENTS}));
     } else if (cardStatus.cardState == CardStatus::STATE_PRESENT) {
-        ASSERT_TRUE(CheckAnyOfErrors(
-                radioRsp_network->rspInfo.error,
-                {RadioError::INVALID_ARGUMENTS, RadioError::REQUEST_NOT_SUPPORTED}));
+        ASSERT_TRUE(
+                CheckAnyOfErrors(radioRsp_network->rspInfo.error, {RadioError::INVALID_ARGUMENTS}));
     }
 }
 
@@ -1142,20 +1062,9 @@
 TEST_P(RadioNetworkTest, startNetworkScan_InvalidPeriodicity2) {
     serial = GetRandomSerialNumber();
 
-    RadioAccessSpecifierBands bandP900 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_P900});
-    RadioAccessSpecifierBands band850 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_850});
-    RadioAccessSpecifier specifierP900 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = bandP900, .channels = {1, 2}};
-    RadioAccessSpecifier specifier850 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = band850, .channels = {128, 129}};
-
     NetworkScanRequest request = {.type = NetworkScanRequest::SCAN_TYPE_ONE_SHOT,
                                   .interval = 60,
-                                  .specifiers = {specifierP900, specifier850},
+                                  .specifiers = {::EUTRAN_SPECIFIER_17, ::EUTRAN_SPECIFIER_20},
                                   .maxSearchTime = 600,
                                   .incrementalResults = true,
                                   .incrementalResultsPeriodicity = 11};
@@ -1171,9 +1080,8 @@
         ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
                                      {RadioError::SIM_ABSENT, RadioError::INVALID_ARGUMENTS}));
     } else if (cardStatus.cardState == CardStatus::STATE_PRESENT) {
-        ASSERT_TRUE(CheckAnyOfErrors(
-                radioRsp_network->rspInfo.error,
-                {RadioError::INVALID_ARGUMENTS, RadioError::REQUEST_NOT_SUPPORTED}));
+        ASSERT_TRUE(
+                CheckAnyOfErrors(radioRsp_network->rspInfo.error, {RadioError::INVALID_ARGUMENTS}));
     }
 }
 
@@ -1183,20 +1091,9 @@
 TEST_P(RadioNetworkTest, startNetworkScan_GoodRequest1) {
     serial = GetRandomSerialNumber();
 
-    RadioAccessSpecifierBands bandP900 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_P900});
-    RadioAccessSpecifierBands band850 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_850});
-    RadioAccessSpecifier specifierP900 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = bandP900, .channels = {1, 2}};
-    RadioAccessSpecifier specifier850 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = band850, .channels = {128, 129}};
-
     NetworkScanRequest request = {.type = NetworkScanRequest::SCAN_TYPE_ONE_SHOT,
                                   .interval = 60,
-                                  .specifiers = {specifierP900, specifier850},
+                                  .specifiers = {::EUTRAN_SPECIFIER_17, ::EUTRAN_SPECIFIER_20},
                                   .maxSearchTime = 360,
                                   .incrementalResults = false,
                                   .incrementalResultsPeriodicity = 10};
@@ -1213,8 +1110,7 @@
                                      {RadioError::NONE, RadioError::SIM_ABSENT}));
     } else if (cardStatus.cardState == CardStatus::STATE_PRESENT) {
         ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
-                                     {RadioError::NONE, RadioError::INVALID_ARGUMENTS,
-                                      RadioError::REQUEST_NOT_SUPPORTED}));
+                                     {RadioError::NONE, RadioError::INVALID_ARGUMENTS}));
     }
 
     if (radioRsp_network->rspInfo.error == RadioError::NONE) {
@@ -1229,20 +1125,9 @@
 TEST_P(RadioNetworkTest, startNetworkScan_GoodRequest2) {
     serial = GetRandomSerialNumber();
 
-    RadioAccessSpecifierBands bandP900 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_P900});
-    RadioAccessSpecifierBands band850 =
-            RadioAccessSpecifierBands::make<RadioAccessSpecifierBands::geranBands>(
-                    {GeranBands::BAND_850});
-    RadioAccessSpecifier specifierP900 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = bandP900, .channels = {1, 2}};
-    RadioAccessSpecifier specifier850 = {
-            .accessNetwork = AccessNetwork::GERAN, .bands = band850, .channels = {128, 129}};
-
     NetworkScanRequest request = {.type = NetworkScanRequest::SCAN_TYPE_ONE_SHOT,
                                   .interval = 60,
-                                  .specifiers = {specifierP900, specifier850},
+                                  .specifiers = {::EUTRAN_SPECIFIER_17, ::EUTRAN_SPECIFIER_20},
                                   .maxSearchTime = 360,
                                   .incrementalResults = false,
                                   .incrementalResultsPeriodicity = 10,
@@ -1260,8 +1145,7 @@
                                      {RadioError::NONE, RadioError::SIM_ABSENT}));
     } else if (cardStatus.cardState == CardStatus::STATE_PRESENT) {
         ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
-                                     {RadioError::NONE, RadioError::INVALID_ARGUMENTS,
-                                      RadioError::REQUEST_NOT_SUPPORTED}));
+                                     {RadioError::NONE, RadioError::INVALID_ARGUMENTS}));
     }
 
     if (radioRsp_network->rspInfo.error == RadioError::NONE) {
@@ -1278,21 +1162,23 @@
 
     // can't camp on nonexistent MCCMNC, so we expect this to fail.
     ndk::ScopedAStatus res =
-            radio_network->setNetworkSelectionModeManual(serial, "123456", AccessNetwork::GERAN);
+            radio_network->setNetworkSelectionModeManual(serial, "123456", AccessNetwork::EUTRAN);
     EXPECT_EQ(std::cv_status::no_timeout, wait());
     EXPECT_EQ(RadioResponseType::SOLICITED, radioRsp_network->rspInfo.type);
     EXPECT_EQ(serial, radioRsp_network->rspInfo.serial);
 
     if (cardStatus.cardState == CardStatus::STATE_ABSENT) {
-        ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
-                                     {RadioError::NONE, RadioError::ILLEGAL_SIM_OR_ME,
-                                      RadioError::INVALID_ARGUMENTS, RadioError::INVALID_STATE},
-                                     CHECK_GENERAL_ERROR));
+        ASSERT_TRUE(CheckAnyOfErrors(
+                radioRsp_network->rspInfo.error,
+                {RadioError::NONE, RadioError::ILLEGAL_SIM_OR_ME, RadioError::INVALID_ARGUMENTS,
+                 RadioError::INVALID_STATE, RadioError::RADIO_NOT_AVAILABLE, RadioError::NO_MEMORY,
+                 RadioError::INTERNAL_ERR, RadioError::SYSTEM_ERR, RadioError::CANCELLED}));
     } else if (cardStatus.cardState == CardStatus::STATE_PRESENT) {
-        ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
-                                     {RadioError::NONE, RadioError::RADIO_NOT_AVAILABLE,
-                                      RadioError::INVALID_ARGUMENTS, RadioError::INVALID_STATE},
-                                     CHECK_GENERAL_ERROR));
+        ASSERT_TRUE(CheckAnyOfErrors(
+                radioRsp_network->rspInfo.error,
+                {RadioError::NONE, RadioError::RADIO_NOT_AVAILABLE, RadioError::INVALID_ARGUMENTS,
+                 RadioError::INVALID_STATE, RadioError::NO_MEMORY, RadioError::INTERNAL_ERR,
+                 RadioError::SYSTEM_ERR, RadioError::CANCELLED}));
     }
 }
 
diff --git a/radio/config/1.0/vts/functional/OWNERS b/radio/config/1.0/vts/functional/OWNERS
deleted file mode 100644
index badd6d7..0000000
--- a/radio/config/1.0/vts/functional/OWNERS
+++ /dev/null
@@ -1,6 +0,0 @@
-# Bug component: 20868
-jminjie@google.com
-sarahchin@google.com
-amitmahajan@google.com
-shuoq@google.com
-jackyu@google.com
diff --git a/radio/config/1.1/vts/OWNERS b/radio/config/1.1/vts/OWNERS
deleted file mode 100644
index 4109967..0000000
--- a/radio/config/1.1/vts/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 20868
-include /radio/1.0/vts/OWNERS
diff --git a/radio/config/1.2/vts/OWNERS b/radio/config/1.2/vts/OWNERS
deleted file mode 100644
index 4109967..0000000
--- a/radio/config/1.2/vts/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 20868
-include /radio/1.0/vts/OWNERS
diff --git a/rebootescrow/OWNERS b/rebootescrow/OWNERS
new file mode 100644
index 0000000..c9701ff
--- /dev/null
+++ b/rebootescrow/OWNERS
@@ -0,0 +1,4 @@
+# Bug component: 63928581
+
+kroot@google.com
+paulcrowley@google.com
diff --git a/rebootescrow/aidl/default/OWNERS b/rebootescrow/aidl/default/OWNERS
deleted file mode 100644
index c5288d6..0000000
--- a/rebootescrow/aidl/default/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-kroot@google.com
-paulcrowley@google.com
diff --git a/rebootescrow/aidl/vts/OWNERS b/rebootescrow/aidl/vts/OWNERS
deleted file mode 100644
index c5288d6..0000000
--- a/rebootescrow/aidl/vts/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-kroot@google.com
-paulcrowley@google.com
diff --git a/renderscript/1.0/vts/functional/OWNERS b/renderscript/OWNERS
similarity index 84%
rename from renderscript/1.0/vts/functional/OWNERS
rename to renderscript/OWNERS
index d785790..443ebff 100644
--- a/renderscript/1.0/vts/functional/OWNERS
+++ b/renderscript/OWNERS
@@ -1,6 +1,6 @@
 # Bug component: 43047
+
 butlermichael@google.com
 dgross@google.com
-jeanluc@google.com
 miaowang@google.com
 xusongw@google.com
diff --git a/scripts/OWNERS b/scripts/OWNERS
new file mode 100644
index 0000000..a07824e
--- /dev/null
+++ b/scripts/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 298954331
+
+include platform/hardware/interfaces:/OWNERS
diff --git a/secure_element/aidl/vts/VtsHalSecureElementTargetTest.cpp b/secure_element/aidl/vts/VtsHalSecureElementTargetTest.cpp
index 97b4e27..9678da4 100644
--- a/secure_element/aidl/vts/VtsHalSecureElementTargetTest.cpp
+++ b/secure_element/aidl/vts/VtsHalSecureElementTargetTest.cpp
@@ -293,11 +293,13 @@
     std::vector<uint8_t> response;
     LogicalChannelResponse logical_channel_response;
 
+    /* Temporaly disable this check to clarify Basic Channel behavior (b/300502872)
     // Note: no channel is opened for this test
     // transmit() will return an empty response with the error
     // code CHANNEL_NOT_AVAILABLE when the SE cannot be
     // communicated with.
     EXPECT_ERR(secure_element_->transmit(kDataApdu, &response));
+    */
 
     EXPECT_OK(secure_element_->openLogicalChannel(kSelectableAid, 0x00, &logical_channel_response));
     EXPECT_GE(logical_channel_response.selectResponse.size(), 2u);
diff --git a/security/README.md b/security/README.md
new file mode 100644
index 0000000..c5b5ba8
--- /dev/null
+++ b/security/README.md
@@ -0,0 +1,109 @@
+# Security-Related HALs
+
+The `security/` subdirectory holds various security-related HALs.  (The final two sections of this
+document also describe security-related HALs that are in other places under `hardware/interfaces/`.)
+
+The most significant HAL is KeyMint (**`IKeyMintDevice`** in the
+`hardware/interfaces/security/keymint/` directory), which allows access to cryptographic
+functionality where the key material is restricted to a secure environment.  This functionality is
+used by Android system services, and is also made available to apps via Android Keystore.
+
+A KeyMint implementation (or an implementation of its predecessor, Keymaster) that runs in an
+isolated execution environment (e.g. ARM TrustZone) is required for most Android devices; see [CDD
+9.11](https://source.android.com/docs/compatibility/13/android-13-cdd#911_keys_and_credentials).
+
+A device may optionally also support a second KeyMint instance, running in a dedicated secure
+processor; this is known as StrongBox ([CDD
+9.11.2](https://source.android.com/docs/compatibility/13/android-13-cdd#9112_strongbox)).
+
+Two specific features of KeyMint are worth highlighting, as they have an impact on the other
+security-related HALs:
+
+- KeyMint supports keys that can only be used when the operation is authenticated by the user,
+  either by their lock screen knowledge factor (LSKF, e.g. PIN or pattern) or by a strong biometric
+  (e.g. fingerprint).
+- KeyMint supports *attestation* of public keys: when an asymmetric keypair is created, the secure
+  environment produces a chain of signed certificates:
+  - starting from a trusted root certificate
+  - terminating in a leaf certificate that holds the public key; this leaf certificate may also
+    describe the state of the device and the policies attached to the key.
+
+## Authentication Verification
+
+User authentication must also take place in a secure environment (see the final section below), but
+the results of that authentication are communicated to KeyMint via Android.  As such, the
+authentication result (a *hardware auth token*) is signed with a per-boot shared HMAC key known only
+to the secure components, so that it's authenticity can be verified.
+
+If an authenticator, for example GateKeeper (described by the **`IGatekeeper`** HAL in
+`hardware/interfaces/gatekeeper/`), is co-located in the same secure environment as KeyMint, it can
+use a local, vendor-specific, method to communicate the shared HMAC key.
+
+However, if the authenticator is in a different environment than the KeyMint instance then a local
+communication mechanism may not be possible.  For example, a StrongBox KeyMint instance running in a
+separate secure processor may not have a communication channel with a TEE on the main processor.
+
+To allow for this, the **`ISharedSecret`** HAL (in `hardware/interfaces/security/sharedsecret`)
+describes an N-party shared key agreement protocol for per-boot derivation of the shared HMAC key,
+based on a pre-provisioned shared secret.  This HAL can be implemented by any security component
+&ndash; whether KeyMint instance or authenticator &ndash; that needs access to the shared HMAC key.
+
+User authentication operations are also timestamped, but a StrongBox KeyMint instance may not have
+access to a secure time source that is aligned with the authenticator's time source.
+
+To allow for this, the **`ISecureClock`** HAL (in `hardware/interfaces/secureclock`) describes a
+challenge-based timestamp authentication protocol.  This HAL is optional; it need only be
+implemented if there is a KeyMint instance without a secure source of time.
+
+## Attestation Key Provisioning
+
+As noted above, key generation may also generate an attestation certificate chain, which requires
+that the secure environment have access to a signing key which in turn chains back to the Google
+root.
+
+Historically these signing keys were created by Google and provided to vendors for installation in
+batches of devices (to prevent their use as unique device identifiers).  However, this mechanism had
+significant disadvantages, as it required secure handling of key material and only allowed for
+coarse-grained revocation.
+
+The remote key provisioning HAL (**`IRemotelyProvisionedComponent`** in
+`hardware/interfaces/security/rkp/`) provides a mechanism whereby signing certificates for
+attestation can be retrieved at runtime from Google servers based on pre-registered device identity
+information.  This mechanism is used to provision certificates for KeyMint's signing keys, but is
+not restricted to that purpose; it can also be used in other scenarios where keys need to be
+provisioned (for example, for [Widevine](https://developers.google.com/widevine/drm/overview)).
+
+## Keymaster
+
+The Keymaster HAL (**`IKeymasterDevice`** in `hardware/interfaces/keymaster/`) is the historical
+ancestor of many of the HALs here (and may still be present on older devices).  Its functionality is
+effectively the union of the following current HALs:
+
+- **`IKeyMintDevice`**
+- **`ISharedSecret`**
+- **`ISecureClock`**
+
+## Related Authentication HALs
+
+Authentication of users needs to happen in a secure environment, using vendor-specific
+functionality, and so involves the use of one of the following HALs (all of which are outside the
+`security/` subdirectory).
+
+- The **`IGatekeeper`** HAL (in `hardware/interfaces/gatekeeper/`) provides user authentication
+  functionality based on the user's lock-screen knowledge factor (LSKF), including throttling
+  behaviour to prevent attacks.  Authentication tokens produced by this HAL are consumed by KeyMint,
+  validated using the shared HMAC key described above.
+  - The optional **`IWeaver`** HAL (in `hardware/interfaces/weaver`) improves the security of LSKF
+    authentication by converting the user's LSKF into a *synthetic password* via hashing and
+    stretching. This is required to be implemented on a separate secure element, which prevents
+    offline attacks on Gatekeeper storage. Note that Weaver does not directly interact with KeyMint;
+    the synthetic password is fed into Gatekeeper in place of the plain user password, and then
+    Gatekeeper interacts with KeyMint as normal.
+- The **`IFingerprint`** and **`IFace`** HAL definitions (under `hardware/interfaces/biometrics/`)
+  allow access to biometric authentication functionality that is implemented in a secure
+  environment.  Authentication tokens produced by these HALs are consumed by KeyMint, validated
+  using the shared HMAC key described above.
+- The optional **`IConfirmationUI`** HAL (in `hardware/interfaces/confirmationui`) supports
+  functionality where the user confirms that they have seen a specific message in a secure manner.
+  Confirmation tokens produced by this HAL are consumed by KeyMint, validated using the shared HMAC
+  key described above.
diff --git a/security/keymint/aidl/android/hardware/security/keymint/IKeyMintDevice.aidl b/security/keymint/aidl/android/hardware/security/keymint/IKeyMintDevice.aidl
index 2e4fc15..aeb0163 100644
--- a/security/keymint/aidl/android/hardware/security/keymint/IKeyMintDevice.aidl
+++ b/security/keymint/aidl/android/hardware/security/keymint/IKeyMintDevice.aidl
@@ -379,6 +379,12 @@
      *   validate it against the key material.  In the event of a mismatch, importKey must return
      *   ErrorCode::IMPORT_PARAMETER_MISMATCH.
      *
+     * o Tag::EC_CURVE is not necessary in the input parameters for import of EC keys. If not
+     *   provided the IKeyMintDevice must deduce the value from the provided key material and add
+     *   the tag and value to the key characteristics.  If Tag::EC_CURVE is provided, the
+     *   IKeyMintDevice must validate it against the key material.  In the event of a mismatch,
+     *   importKey must return ErrorCode::IMPORT_PARAMETER_MISMATCH.
+     *
      * o Tag::RSA_PUBLIC_EXPONENT (for RSA keys only) is not necessary in the input parameters.  If
      *   not provided, the IKeyMintDevice must deduce the value from the provided key material and
      *   add the tag and value to the key characteristics.  If Tag::RSA_PUBLIC_EXPONENT is provided,
diff --git a/security/keymint/aidl/vts/functional/AttestKeyTest.cpp b/security/keymint/aidl/vts/functional/AttestKeyTest.cpp
index 4c46719..cc97c13 100644
--- a/security/keymint/aidl/vts/functional/AttestKeyTest.cpp
+++ b/security/keymint/aidl/vts/functional/AttestKeyTest.cpp
@@ -88,30 +88,6 @@
 
     return imei;
 }
-
-// Use `ro.product.<property>_for_attestation` property for attestation if it is present else
-// fallback to use `ro.product.vendor.<property>` if it is present else fallback to
-// `ro.product.<property>`. Similar logic can be seen in Java method `getVendorDeviceIdProperty`
-// in frameworks/base/core/java/android/os/Build.java.
-template <Tag tag>
-void add_attestation_id(AuthorizationSetBuilder* attestation_id_tags,
-                        TypedTag<TagType::BYTES, tag> tag_type, const char* prop) {
-    ::android::String8 prop_name =
-            ::android::String8::format("ro.product.%s_for_attestation", prop);
-    std::string prop_value = ::android::base::GetProperty(prop_name.c_str(), /* default= */ "");
-    if (!prop_value.empty()) {
-        add_tag_from_prop(attestation_id_tags, tag_type, prop_name.c_str());
-    } else {
-        prop_name = ::android::String8::format("ro.product.vendor.%s", prop);
-        prop_value = ::android::base::GetProperty(prop_name.c_str(), /* default= */ "");
-        if (!prop_value.empty()) {
-            add_tag_from_prop(attestation_id_tags, tag_type, prop_name.c_str());
-        } else {
-            prop_name = ::android::String8::format("ro.product.%s", prop);
-            add_tag_from_prop(attestation_id_tags, tag_type, prop_name.c_str());
-        }
-    }
-}
 }  // namespace
 
 class AttestKeyTest : public KeyMintAidlTestBase {
diff --git a/security/keymint/aidl/vts/functional/AuthTest.cpp b/security/keymint/aidl/vts/functional/AuthTest.cpp
index d5c6d2a..eb5db68 100644
--- a/security/keymint/aidl/vts/functional/AuthTest.cpp
+++ b/security/keymint/aidl/vts/functional/AuthTest.cpp
@@ -350,14 +350,14 @@
 
     // Wait for long enough that the hardware auth token expires.
     sleep(timeout_secs + 1);
-    if (!timestamp_token_required_) {
-        // KeyMint implementation has its own clock, and can immediately detect timeout.
-        EXPECT_EQ(ErrorCode::KEY_USER_NOT_AUTHENTICATED,
-                  Begin(KeyPurpose::ENCRYPT, keyblob, params, &out_params, hat));
-    } else {
-        // KeyMint implementation has no clock, so only detects timeout via timestamp token provided
-        // on update()/finish().
-        ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, keyblob, params, &out_params, hat));
+
+    auto begin_result = Begin(KeyPurpose::ENCRYPT, keyblob, params, &out_params, hat);
+    if (begin_result == ErrorCode::OK) {
+        // If begin() succeeds despite the out-of-date HAT, that must mean that the KeyMint
+        // device doesn't have its own clock.  In that case, it only detects timeout via a
+        // timestamp token provided on update()/finish()
+        ASSERT_TRUE(timestamp_token_required_);
+
         secureclock::TimeStampToken time_token;
         EXPECT_EQ(ErrorCode::OK,
                   GetReturnErrorCode(clock_->generateTimeStamp(challenge_, &time_token)));
@@ -365,6 +365,9 @@
         string output;
         EXPECT_EQ(ErrorCode::KEY_USER_NOT_AUTHENTICATED,
                   Finish(message, {} /* signature */, &output, hat, time_token));
+    } else {
+        // The KeyMint implementation may have its own clock that can immediately detect timeout.
+        ASSERT_EQ(ErrorCode::KEY_USER_NOT_AUTHENTICATED, begin_result);
     }
 }
 
diff --git a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp
index 5f8ec0e..3a8a1e8 100644
--- a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp
+++ b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp
@@ -841,7 +841,7 @@
         int vendor_api_level = property_get_int32("ro.vendor.api_level", 0);
         if (SecLevel() == SecurityLevel::STRONGBOX) {
             // This is known to be broken on older vendor implementations.
-            if (vendor_api_level < __ANDROID_API_T__) {
+            if (vendor_api_level <= __ANDROID_API_U__) {
                 compare_output = false;
             } else {
                 additional_information = " (b/194134359) ";
diff --git a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h
index 8934a57..9778b3d 100644
--- a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h
+++ b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h
@@ -454,6 +454,29 @@
                              ::android::PrintInstanceNameToString);                  \
     GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(name);
 
+// Use `ro.product.<property>_for_attestation` property for attestation if it is present else
+// fallback to use `ro.product.vendor.<property>` if it is present else fallback to
+// `ro.product.<property>`. Similar logic can be seen in Java method `getVendorDeviceIdProperty`
+// in frameworks/base/core/java/android/os/Build.java.
+template <Tag tag>
+void add_attestation_id(AuthorizationSetBuilder* attestation_id_tags,
+                        TypedTag<TagType::BYTES, tag> tag_type, const char* prop) {
+    ::android::String8 prop_name =
+            ::android::String8::format("ro.product.%s_for_attestation", prop);
+    std::string prop_value = ::android::base::GetProperty(prop_name.c_str(), /* default= */ "");
+    if (!prop_value.empty()) {
+        add_tag_from_prop(attestation_id_tags, tag_type, prop_name.c_str());
+    } else {
+        prop_name = ::android::String8::format("ro.product.vendor.%s", prop);
+        prop_value = ::android::base::GetProperty(prop_name.c_str(), /* default= */ "");
+        if (!prop_value.empty()) {
+            add_tag_from_prop(attestation_id_tags, tag_type, prop_name.c_str());
+        } else {
+            prop_name = ::android::String8::format("ro.product.%s", prop);
+            add_tag_from_prop(attestation_id_tags, tag_type, prop_name.c_str());
+        }
+    }
+}
 }  // namespace test
 
 }  // namespace aidl::android::hardware::security::keymint
diff --git a/security/keymint/aidl/vts/functional/KeyMintTest.cpp b/security/keymint/aidl/vts/functional/KeyMintTest.cpp
index 022dd3f..de563c4 100644
--- a/security/keymint/aidl/vts/functional/KeyMintTest.cpp
+++ b/security/keymint/aidl/vts/functional/KeyMintTest.cpp
@@ -2082,11 +2082,6 @@
  * attestation extension.
  */
 TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
-    if (is_gsi_image()) {
-        // GSI sets up a standard set of device identifiers that may not match
-        // the device identifiers held by the device.
-        GTEST_SKIP() << "Test not applicable under GSI";
-    }
     auto challenge = "hello";
     auto app_id = "foo";
     auto subject = "cert subj 2";
@@ -2106,38 +2101,12 @@
 
     // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
     auto extra_tags = AuthorizationSetBuilder();
-    // Use ro.product.brand_for_attestation property for attestation if it is present else fallback
-    // to ro.product.brand
-    std::string prop_value =
-            ::android::base::GetProperty("ro.product.brand_for_attestation", /* default= */ "");
-    if (!prop_value.empty()) {
-        add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND,
-                          "ro.product.brand_for_attestation");
-    } else {
-        add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
-    }
-    add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
-    // Use ro.product.name_for_attestation property for attestation if it is present else fallback
-    // to ro.product.name
-    prop_value = ::android::base::GetProperty("ro.product.name_for_attestation", /* default= */ "");
-    if (!prop_value.empty()) {
-        add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT,
-                          "ro.product.name_for_attestation");
-    } else {
-        add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
-    }
+    add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_BRAND, "brand");
+    add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "device");
+    add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "name");
+    add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer");
+    add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_MODEL, "model");
     add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
-    add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
-    // Use ro.product.model_for_attestation property for attestation if it is present else fallback
-    // to ro.product.model
-    prop_value =
-            ::android::base::GetProperty("ro.product.model_for_attestation", /* default= */ "");
-    if (!prop_value.empty()) {
-        add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL,
-                          "ro.product.model_for_attestation");
-    } else {
-        add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
-    }
 
     for (const KeyParameter& tag : extra_tags) {
         SCOPED_TRACE(testing::Message() << "tag-" << tag);
@@ -2611,16 +2580,16 @@
 /*
  * NewKeyGenerationTest.EcdsaMissingCurve
  *
- * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
+ * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V3.
  */
 TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
-    if (AidlVersion() < 2) {
+    if (AidlVersion() < 3) {
         /*
          * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
          * However, this was not checked at the time so we can only be strict about checking this
-         * for implementations of KeyMint version 2 and above.
+         * for implementations of KeyMint version 3 and above.
          */
-        GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
+        GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v3";
     }
     /* If EC_CURVE not provided, generateKey
      * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
@@ -4148,6 +4117,42 @@
 }
 
 /*
+ * ImportKeyTest.EcdsaSuccessCurveNotSpecified
+ *
+ * Verifies that importing and using an ECDSA P-256 key pair works correctly
+ * when the EC_CURVE is not explicitly specified.
+ */
+TEST_P(ImportKeyTest, EcdsaSuccessCurveNotSpecified) {
+    if (AidlVersion() < 4) {
+        /*
+         * The KeyMint spec before V4 was not clear as to whether EC_CURVE was optional on import of
+         * EC keys. However, this was not checked at the time so we can only be strict about
+         * checking this for implementations of KeyMint version 4 and above.
+         */
+        GTEST_SKIP() << "Skipping EC_CURVE on import only strict since KeyMint v4";
+    }
+
+    ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
+                                               .Authorization(TAG_NO_AUTH_REQUIRED)
+                                               .Authorization(TAG_ALGORITHM, Algorithm::EC)
+                                               .SigningKey()
+                                               .Digest(Digest::SHA_2_256)
+                                               .SetDefaultValidity(),
+                                       KeyFormat::PKCS8, ec_256_key));
+
+    CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
+    CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
+    CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
+
+    CheckOrigin();
+
+    string message(32, 'a');
+    auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
+    string signature = SignMessage(message, params);
+    LocalVerifyMessage(message, signature, params);
+}
+
+/*
  * ImportKeyTest.EcdsaP256RFC5915Success
  *
  * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
@@ -4792,7 +4797,7 @@
 
         EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
         string result;
-        EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
+        EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
         EXPECT_EQ(0U, result.size());
     }
 }
@@ -5300,7 +5305,7 @@
 
         EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
         string result;
-        EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
+        EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
         EXPECT_EQ(0U, result.size());
     }
 }
@@ -5367,7 +5372,7 @@
                                                                 .Digest(Digest::SHA_2_256)
                                                                 .Padding(PaddingMode::RSA_OAEP)));
     string result;
-    EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
+    EXPECT_NE(ErrorCode::OK, Finish(ciphertext, &result));
     EXPECT_EQ(0U, result.size());
 }
 
@@ -5437,7 +5442,7 @@
 
         EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
         string result;
-        EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
+        EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
         EXPECT_EQ(0U, result.size());
     }
 }
@@ -5481,7 +5486,7 @@
 
     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
     string result;
-    EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
+    EXPECT_NE(ErrorCode::OK, Finish(ciphertext, &result));
     EXPECT_EQ(0U, result.size());
 }
 
@@ -5613,7 +5618,7 @@
 
     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
     string result;
-    EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
+    EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
     EXPECT_EQ(0U, result.size());
 }
 
diff --git a/security/keymint/support/remote_prov_utils.cpp b/security/keymint/support/remote_prov_utils.cpp
index 780c3d2..34f7ce4 100644
--- a/security/keymint/support/remote_prov_utils.cpp
+++ b/security/keymint/support/remote_prov_utils.cpp
@@ -962,6 +962,20 @@
     return signedRequest->value();
 }
 
+ErrMsgOr<hwtrust::DiceChain::Kind> getDiceChainKind() {
+    int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
+    switch (vendor_api_level) {
+        case __ANDROID_API_T__:
+            return hwtrust::DiceChain::Kind::kVsr13;
+        case __ANDROID_API_U__:
+            return hwtrust::DiceChain::Kind::kVsr14;
+        case __ANDROID_API_V__:
+            return hwtrust::DiceChain::Kind::kVsr15;
+        default:
+            return "Unsupported vendor API level: " + std::to_string(vendor_api_level);
+    }
+}
+
 ErrMsgOr<bytevec> parseAndValidateAuthenticatedRequest(const std::vector<uint8_t>& request,
                                                        const std::vector<uint8_t>& challenge) {
     auto [parsedRequest, _, csrErrMsg] = cppbor::parse(request);
@@ -996,7 +1010,12 @@
     }
 
     // DICE chain is [ pubkey, + DiceChainEntry ].
-    auto diceContents = validateBcc(diceCertChain, hwtrust::DiceChain::Kind::kVsr14);
+    auto diceChainKind = getDiceChainKind();
+    if (!diceChainKind) {
+        return diceChainKind.message();
+    }
+
+    auto diceContents = validateBcc(diceCertChain, *diceChainKind);
     if (!diceContents) {
         return diceContents.message() + "\n" + prettyPrint(diceCertChain);
     }
diff --git a/security/rkp/aidl/Android.bp b/security/rkp/aidl/Android.bp
index e2ce649..e9e2021 100644
--- a/security/rkp/aidl/Android.bp
+++ b/security/rkp/aidl/Android.bp
@@ -28,6 +28,10 @@
         },
         rust: {
             enabled: true,
+            apex_available: [
+                "//apex_available:platform",
+                "com.android.virt",
+            ],
         },
     },
     versions_with_info: [
diff --git a/security/rkp/aidl/android/hardware/security/keymint/DeviceInfo.aidl b/security/rkp/aidl/android/hardware/security/keymint/DeviceInfo.aidl
index 8456148..f668536 100644
--- a/security/rkp/aidl/android/hardware/security/keymint/DeviceInfo.aidl
+++ b/security/rkp/aidl/android/hardware/security/keymint/DeviceInfo.aidl
@@ -32,79 +32,9 @@
      * non-canonical to group similar entries semantically.
      *
      * The DeviceInfo has changed across versions 1, 2, and 3 of the HAL. All versions of the
-     * DeviceInfo CDDL are described as follows. Please refer to the CDDL structure version
-     * that corresponds to the HAL version you are working with:
+     * DeviceInfo CDDL are described in the DeviceInfoV*.cddl files. Please refer to the CDDL
+     * structure version that corresponds to the HAL version you are working with.
      *
-     * Version 3, introduced in Android 14:
-     *     DeviceInfo = {
-     *         "brand" : tstr,
-     *         "manufacturer" : tstr,
-     *         "product" : tstr,
-     *         "model" : tstr,
-     *         "device" : tstr,
-     *         "vb_state" : "green" / "yellow" / "orange",    ; Taken from the AVB values
-     *         "bootloader_state" : "locked" / "unlocked",    ; Taken from the AVB values
-     *         "vbmeta_digest": bstr,                         ; Taken from the AVB values
-     *         ? "os_version" : tstr,                         ; Same as
-     *                                                        ; android.os.Build.VERSION.release
-     *                                                        ; Not optional for TEE.
-     *         "system_patch_level" : uint,     ; YYYYMM, must match KeyMint OS_PATCHLEVEL
-     *         "boot_patch_level" : uint,       ; YYYYMMDD, must match KeyMint BOOT_PATCHLEVEL
-     *         "vendor_patch_level" : uint,     ; YYYYMMDD, must match KeyMint VENDOR_PATCHLEVEL
-     *         "security_level" : "tee" / "strongbox",
-     *         "fused": 1 / 0,  ; 1 if secure boot is enforced for the processor that the IRPC
-     *                          ; implementation is contained in. 0 otherwise.
-     *     }
-     *
-     * ---------------------------------------------------------------------------------------------
-     *
-     * Version 2, introduced in Android 13:
-     *     DeviceInfo = {
-     *         "brand" : tstr,
-     *         "manufacturer" : tstr,
-     *         "product" : tstr,
-     *         "model" : tstr,
-     *         "device" : tstr,
-     *         "vb_state" : "green" / "yellow" / "orange",    ; Taken from the AVB values
-     *         "bootloader_state" : "locked" / "unlocked",    ; Taken from the AVB values
-     *         "vbmeta_digest": bstr,                         ; Taken from the AVB values
-     *         ? "os_version" : tstr,                         ; Same as
-     *                                                        ; android.os.Build.VERSION.release
-     *                                                        ; Not optional for TEE.
-     *         "system_patch_level" : uint,     ; YYYYMM, must match KeyMint OS_PATCHLEVEL
-     *         "boot_patch_level" : uint,       ; YYYYMMDD, must match KeyMint BOOT_PATCHLEVEL
-     *         "vendor_patch_level" : uint,     ; YYYYMMDD, must match KeyMint VENDOR_PATCHLEVEL
-     *         "version" : 2,                                 ; The CDDL schema version.
-     *         "security_level" : "tee" / "strongbox",
-     *         "fused": 1 / 0,  ; 1 if secure boot is enforced for the processor that the IRPC
-     *                          ; implementation is contained in. 0 otherwise.
-     *
-     * ---------------------------------------------------------------------------------------------
-     *
-     * Version 1, introduced in Android 12:
-     *     DeviceInfo = {
-     *         ? "brand" : tstr,
-     *         ? "manufacturer" : tstr,
-     *         ? "product" : tstr,
-     *         ? "model" : tstr,
-     *         ? "board" : tstr,
-     *         ? "vb_state" : "green" / "yellow" / "orange",  ; Taken from the AVB values
-     *         ? "bootloader_state" : "locked" / "unlocked",  ; Taken from the AVB values
-     *         ? "vbmeta_digest": bstr,                       ; Taken from the AVB values
-     *         ? "os_version" : tstr,                         ; Same as
-     *                                                        ; android.os.Build.VERSION.release
-     *         ? "system_patch_level" : uint,     ; YYYYMM, must match KeyMint OS_PATCHLEVEL
-     *         ? "boot_patch_level" : uint,       ; YYYYMMDD, must match KeyMint BOOT_PATCHLEVEL
-     *         ? "vendor_patch_level" : uint,     ; YYYYMMDD, must match KeyMint VENDOR_PATCHLEVEL
-     *         "version" : 1,                                 ; The CDDL schema version.
-     *         "security_level" : "tee" / "strongbox"
-     *         "att_id_state": "locked" / "open",  ; Attestation IDs State. If "locked", this
-     *                                             ; indicates a device's attestable IDs are
-     *                                             ; factory-locked and immutable. If "open",
-     *                                             ; this indicates the device is still in a
-     *                                             ; provisionable state and the attestable IDs
-     *                                             ; are not yet frozen.
-     *     }
      */
     byte[] deviceInfo;
 }
diff --git a/security/rkp/aidl/android/hardware/security/keymint/DeviceInfoV1.cddl b/security/rkp/aidl/android/hardware/security/keymint/DeviceInfoV1.cddl
new file mode 100644
index 0000000..056316b
--- /dev/null
+++ b/security/rkp/aidl/android/hardware/security/keymint/DeviceInfoV1.cddl
@@ -0,0 +1,24 @@
+; Version 1, introduced in Android 12:
+DeviceInfo = {
+    ? "brand" : tstr,
+    ? "manufacturer" : tstr,
+    ? "product" : tstr,
+    ? "model" : tstr,
+    ? "board" : tstr,
+    ? "vb_state" : "green" / "yellow" / "orange",  ; Taken from the AVB values
+    ? "bootloader_state" : "locked" / "unlocked",  ; Taken from the AVB values
+    ? "vbmeta_digest": bstr,                       ; Taken from the AVB values
+    ? "os_version" : tstr,                         ; Same as
+                                                   ; android.os.Build.VERSION.release
+    ? "system_patch_level" : uint,     ; YYYYMM, must match KeyMint OS_PATCHLEVEL
+    ? "boot_patch_level" : uint,       ; YYYYMMDD, must match KeyMint BOOT_PATCHLEVEL
+    ? "vendor_patch_level" : uint,     ; YYYYMMDD, must match KeyMint VENDOR_PATCHLEVEL
+    "version" : 1,                                 ; The CDDL schema version.
+    "security_level" : "tee" / "strongbox"
+    "att_id_state": "locked" / "open",  ; Attestation IDs State. If "locked", this
+                                        ; indicates a device's attestable IDs are
+                                        ; factory-locked and immutable. If "open",
+                                        ; this indicates the device is still in a
+                                        ; provisionable state and the attestable IDs
+                                        ; are not yet frozen.
+}
diff --git a/security/rkp/aidl/android/hardware/security/keymint/DeviceInfoV2.cddl b/security/rkp/aidl/android/hardware/security/keymint/DeviceInfoV2.cddl
new file mode 100644
index 0000000..e49471e
--- /dev/null
+++ b/security/rkp/aidl/android/hardware/security/keymint/DeviceInfoV2.cddl
@@ -0,0 +1,21 @@
+; Version 2, introduced in Android 13:
+DeviceInfo = {
+    "brand" : tstr,
+    "manufacturer" : tstr,
+    "product" : tstr,
+    "model" : tstr,
+    "device" : tstr,
+    "vb_state" : "green" / "yellow" / "orange",    ; Taken from the AVB values
+    "bootloader_state" : "locked" / "unlocked",    ; Taken from the AVB values
+    "vbmeta_digest": bstr,                         ; Taken from the AVB values
+    ? "os_version" : tstr,                         ; Same as
+                                                   ; android.os.Build.VERSION.release
+                                                   ; Not optional for TEE.
+    "system_patch_level" : uint,     ; YYYYMM, must match KeyMint OS_PATCHLEVEL
+    "boot_patch_level" : uint,       ; YYYYMMDD, must match KeyMint BOOT_PATCHLEVEL
+    "vendor_patch_level" : uint,     ; YYYYMMDD, must match KeyMint VENDOR_PATCHLEVEL
+    "version" : 2,                                 ; The CDDL schema version.
+    "security_level" : "tee" / "strongbox",
+    "fused": 1 / 0,  ; 1 if secure boot is enforced for the processor that the IRPC
+                     ; implementation is contained in. 0 otherwise.
+}
\ No newline at end of file
diff --git a/security/rkp/aidl/android/hardware/security/keymint/DeviceInfoV3.cddl b/security/rkp/aidl/android/hardware/security/keymint/DeviceInfoV3.cddl
new file mode 100644
index 0000000..e841706
--- /dev/null
+++ b/security/rkp/aidl/android/hardware/security/keymint/DeviceInfoV3.cddl
@@ -0,0 +1,20 @@
+; Version 3, introduced in Android 14:
+DeviceInfo = {
+    "brand" : tstr,
+    "manufacturer" : tstr,
+    "product" : tstr,
+    "model" : tstr,
+    "device" : tstr,
+    "vb_state" : "green" / "yellow" / "orange",    ; Taken from the AVB values
+    "bootloader_state" : "locked" / "unlocked",    ; Taken from the AVB values
+    "vbmeta_digest": bstr,                         ; Taken from the AVB values
+    ? "os_version" : tstr,                         ; Same as
+                                                   ; android.os.Build.VERSION.release
+                                                   ; Not optional for TEE.
+    "system_patch_level" : uint,     ; YYYYMM, must match KeyMint OS_PATCHLEVEL
+    "boot_patch_level" : uint,       ; YYYYMMDD, must match KeyMint BOOT_PATCHLEVEL
+    "vendor_patch_level" : uint,     ; YYYYMMDD, must match KeyMint VENDOR_PATCHLEVEL
+    "security_level" : "tee" / "strongbox",
+    "fused": 1 / 0,  ; 1 if secure boot is enforced for the processor that the IRPC
+                     ; implementation is contained in. 0 otherwise.
+}
diff --git a/security/rkp/aidl/android/hardware/security/keymint/MacedPublicKey.aidl b/security/rkp/aidl/android/hardware/security/keymint/MacedPublicKey.aidl
index 1e41d1b..a290817 100644
--- a/security/rkp/aidl/android/hardware/security/keymint/MacedPublicKey.aidl
+++ b/security/rkp/aidl/android/hardware/security/keymint/MacedPublicKey.aidl
@@ -28,33 +28,8 @@
      * only to the secure environment, as proof that the public key was generated by that
      * environment. In CDDL, assuming the contained key is a P-256 public key:
      *
-     *     MacedPublicKey = [                     ; COSE_Mac0
-     *         protected: bstr .cbor { 1 : 5},    ; Algorithm : HMAC-256
-     *         unprotected: { },
-     *         payload : bstr .cbor PublicKey,
-     *         tag : bstr HMAC-256(K_mac, MAC_structure)
-     *     ]
+     * See MacedPublicKey.cddl for CDDL definition.
      *
-     *     ; NOTE: -70000 is deprecated for v3 HAL implementations.
-     *     ; NOTE: Integer encoding is different for Ed25519 and P256 keys:
-     *     ;       - Ed25519 is LE: https://www.rfc-editor.org/rfc/rfc8032#section-3.1
-     *     ;       - P256 is BE: https://www.secg.org/sec1-v2.pdf#page=19 (section 2.3.7)
-     *     PublicKey = {               ; COSE_Key
-     *         1 : 2,                  ; Key type : EC2
-     *         3 : -7,                 ; Algorithm : ES256
-     *         -1 : 1,                 ; Curve : P256
-     *         -2 : bstr,              ; X coordinate, big-endian
-     *         -3 : bstr,              ; Y coordinate, big-endian
-     *         -70000 : nil            ; Presence indicates this is a test key. If set, K_mac is
-     *                                 ; all zeros.
-     *     },
-     *
-     *     MAC_structure = [
-     *         context : "MAC0",
-     *         protected : bstr .cbor { 1 : 5 },
-     *         external_aad : bstr .size 0,
-     *         payload : bstr .cbor PublicKey
-     *     ]
      */
     byte[] macedKey;
 }
diff --git a/security/rkp/aidl/android/hardware/security/keymint/MacedPublicKey.cddl b/security/rkp/aidl/android/hardware/security/keymint/MacedPublicKey.cddl
new file mode 100644
index 0000000..6ae4be4
--- /dev/null
+++ b/security/rkp/aidl/android/hardware/security/keymint/MacedPublicKey.cddl
@@ -0,0 +1,15 @@
+MacedPublicKey = [                     ; COSE_Mac0 [RFC9052 s6.2]
+    protected: bstr .cbor { 1 : 5},    ; Algorithm : HMAC-256
+    unprotected: { },
+    payload : bstr .cbor PublicKey,
+    tag : bstr ; HMAC-256(K_mac, MAC_structure)
+]
+
+MAC_structure = [                      ; [RFC9052 s6.3]
+    context : "MAC0",
+    protected : bstr .cbor { 1 : 5 },
+    external_aad : bstr .size 0,
+    payload : bstr .cbor PublicKey
+]
+
+; INCLUDE PublicKey.cddl for: PublicKey
diff --git a/security/rkp/aidl/android/hardware/security/keymint/PublicKey.cddl b/security/rkp/aidl/android/hardware/security/keymint/PublicKey.cddl
new file mode 100644
index 0000000..4c1050d
--- /dev/null
+++ b/security/rkp/aidl/android/hardware/security/keymint/PublicKey.cddl
@@ -0,0 +1,13 @@
+; NOTE: -70000 is deprecated for v3 HAL implementations.
+; NOTE: Integer encoding is different for Ed25519 and P256 keys:
+;       - Ed25519 is LE: https://www.rfc-editor.org/rfc/rfc8032#section-3.1
+;       - P256 is BE: https://www.secg.org/sec1-v2.pdf#page=19 (section 2.3.7)
+PublicKey = {               ; COSE_Key [RFC9052 s7]
+    1 : 2,                  ; Key type : EC2
+    3 : -7,                 ; Algorithm : ES256
+    -1 : 1,                 ; Curve : P256
+    -2 : bstr,              ; X coordinate, big-endian
+    -3 : bstr,              ; Y coordinate, big-endian
+    ? -70000 : nil          ; Presence indicates this is a test key. If set, K_mac is
+                            ; all zeros.
+}
diff --git a/security/rkp/aidl/android/hardware/security/keymint/generateCertificateRequest.cddl b/security/rkp/aidl/android/hardware/security/keymint/generateCertificateRequest.cddl
index 82930bc..fb11492 100644
--- a/security/rkp/aidl/android/hardware/security/keymint/generateCertificateRequest.cddl
+++ b/security/rkp/aidl/android/hardware/security/keymint/generateCertificateRequest.cddl
@@ -3,25 +3,25 @@
 
 EekChain = [ + SignedSignatureKey, SignedEek ]
 
-SignedSignatureKey = [              ; COSE_Sign1
+SignedSignatureKey = [              ; COSE_Sign1 [RFC9052 s4.2]
     protected: bstr .cbor {
         1 : AlgorithmEdDSA / AlgorithmES256,  ; Algorithm
     },
     unprotected: {},
     payload: bstr .cbor SignatureKeyEd25519 /
                 bstr .cbor SignatureKeyP256,
-    signature: bstr PureEd25519(.cbor SignatureKeySignatureInput) /
-                bstr ECDSA(.cbor SignatureKeySignatureInput)
+    signature: bstr ; PureEd25519(.cbor SignatureKeySignatureInput) /
+                    ; ECDSA(.cbor SignatureKeySignatureInput)
 ]
 
-SignatureKeyEd25519 = {             ; COSE_Key
+SignatureKeyEd25519 = {             ; COSE_Key [RFC9052 s7]
         1 : 1,                         ; Key type : Octet Key Pair
         3 : AlgorithmEdDSA,            ; Algorithm
         -1 : 6,                        ; Curve : Ed25519
         -2 : bstr                      ; Ed25519 public key
 }
 
-SignatureKeyP256 = {                ; COSE_Key
+SignatureKeyP256 = {                ; COSE_Key [RC9052 s7]
         1 : 2,                         ; Key type : EC2
         3 : AlgorithmES256,            ; Algorithm
         -1 : 1,                        ; Curve: P256
@@ -37,16 +37,15 @@
                 bstr .cbor SignatureKeyP256
 ]
 
-; COSE_Sign1
-SignedEek = [
+SignedEek = [                       ; COSE_Sign1 [RFC9052 s4.2]
     protected: bstr .cbor { 1 : AlgorithmEdDSA / AlgorithmES256 },
     unprotected: {},
-    payload: bstr .cbor EekX25519 / .cbor EekP256,
-    signature: bstr PureEd25519(.cbor EekSignatureInput) /
-                bstr ECDSA(.cbor EekSignatureInput)
+    payload: bstr .cbor EekX25519 / EekP256,
+    signature: bstr ; PureEd25519(.cbor EekSignatureInput) /
+                    ; ECDSA(.cbor EekSignatureInput)
 ]
 
-EekX25519 = {            ; COSE_Key
+EekX25519 = {            ; COSE_Key [RFC9052 s7]
     1 : 1,               ; Key type : Octet Key Pair
     2 : bstr             ; KID : EEK ID
     3 : -25,             ; Algorithm : ECDH-ES + HKDF-256
@@ -54,7 +53,7 @@
     -2 : bstr            ; X25519 public key, little-endian
 }
 
-EekP256 = {              ; COSE_Key
+EekP256 = {              ; COSE_Key [RFC9052 s7]
     1 : 2,               ; Key type : EC2
     2 : bstr             ; KID : EEK ID
     3 : -25,             ; Algorithm : ECDH-ES + HKDF-256
@@ -67,13 +66,13 @@
     context: "Signature1",
     body_protected: bstr .cbor { 1 : AlgorithmEdDSA / AlgorithmES256 },
     external_aad: bstr .size 0,
-    payload: bstr .cbor EekX25519 / .cbor EekP256
+    payload: bstr .cbor EekX25519 / EekP256
 ]
 
-AlgorithmES256 = -7      ; RFC 8152 section 8.1
-AlgorithmEdDSA = -8      ; RFC 8152 section 8.2
+AlgorithmES256 = -7      ; [RFC8152 s8.1]
+AlgorithmEdDSA = -8      ; [RFC8152 s8.2]
 
-MacedKeys = [                            ; COSE_Mac0
+MacedKeys = [                            ; COSE_Mac0 [RFC9052 s6.2]
     protected : bstr .cbor {
         1 : 5,                           ; Algorithm : HMAC-256
     },
@@ -83,10 +82,12 @@
     tag: bstr
 ]
 
-KeysToMacStructure = [
+KeysToMacStructure = [                   ; [RFC9052 s6.3]
     context : "MAC0",
     protected : bstr .cbor { 1 : 5 },    ; Algorithm : HMAC-256
     external_aad : bstr .size 0,
     ; Payload is PublicKeys from keysToSign argument, in provided order.
     payload : bstr .cbor [ * PublicKey ]
 ]
+
+; INCLUDE PublicKey.cddl for: PublicKey
diff --git a/security/rkp/aidl/android/hardware/security/keymint/generateCertificateRequestV2.cddl b/security/rkp/aidl/android/hardware/security/keymint/generateCertificateRequestV2.cddl
index ea71f98..15b0442 100644
--- a/security/rkp/aidl/android/hardware/security/keymint/generateCertificateRequestV2.cddl
+++ b/security/rkp/aidl/android/hardware/security/keymint/generateCertificateRequestV2.cddl
@@ -6,7 +6,7 @@
 CsrPayload = [                      ; CBOR Array defining the payload for Csr
     version: 3,                     ; The CsrPayload CDDL Schema version.
     CertificateType,                ; The type of certificate being requested.
-    DeviceInfo,                     ; Defined in DeviceInfo.aidl
+    DeviceInfo,                     ; Defined in the relevant DeviceInfoV*.cddl file.
     KeysToSign,                     ; Provided by the method parameters
 ]
 
@@ -18,7 +18,7 @@
 ;  - "keymint"
 CertificateType = tstr
 
-KeysToSign = [ * PublicKey ]   ; Please see MacedPublicKey.aidl for the PublicKey definition.
+KeysToSign = [ * PublicKey ]   ; Please see PublicKey.cddl for the PublicKey definition.
 
 AuthenticatedRequest<T> = [
     version: 1,              ; The AuthenticatedRequest CDDL Schema version.
@@ -30,7 +30,7 @@
     ]>,
 ]
 
-; COSE_Sign1 (untagged)
+; COSE_Sign1 (untagged) [RFC9052 s4.2]
 SignedData<Data> = [
     protected: bstr .cbor { 1 : AlgorithmEdDSA / AlgorithmES256 / AlgorithmES384 },
     unprotected: {},
@@ -39,7 +39,7 @@
                         ; ECDSA(CDI_Leaf_Priv, SignedDataSigStruct<Data>)
 ]
 
-; Sig_structure for SignedData
+; Sig_structure for SignedData [ RFC9052 s4.4]
 SignedDataSigStruct<Data> = [
     context: "Signature1",
     protected: bstr .cbor { 1 : AlgorithmEdDSA / AlgorithmES256 / AlgorithmES384 },
@@ -90,9 +90,10 @@
 DiceChainEntryPayload = {                    ; CWT [RFC8392]
     1 : tstr,                                ; Issuer
     2 : tstr,                                ; Subject
+    -4670554 : "android.15",                 ; Profile Name
     -4670552 : bstr .cbor PubKeyEd25519 /
             bstr .cbor PubKeyECDSA256 /
-            bstr .cbor PubKeyECDSA384,    ; Subject Public Key
+            bstr .cbor PubKeyECDSA384,       ; Subject Public Key
     -4670553 : bstr                          ; Key Usage
 
     ; NOTE: All of the following fields may be omitted for a "Degenerate DICE Chain", as
@@ -113,7 +114,7 @@
 
 ; Each entry in the DICE chain is a DiceChainEntryPayload signed by the key from the previous
 ; entry in the DICE chain array.
-DiceChainEntry = [                            ; COSE_Sign1 (untagged)
+DiceChainEntry = [                            ; COSE_Sign1 (untagged), [RFC9052 s4.2]
     protected : bstr .cbor { 1 : AlgorithmEdDSA / AlgorithmES256 / AlgorithmES384 },
     unprotected: {},
     payload: bstr .cbor DiceChainEntryPayload,
@@ -135,14 +136,14 @@
 ; NOTE: Integer encoding is different for Ed25519 and P256 keys:
 ;       - Ed25519 is LE: https://www.rfc-editor.org/rfc/rfc8032#section-3.1
 ;       - P256 is BE: https://www.secg.org/sec1-v2.pdf#page=19 (section 2.3.7)
-PubKeyEd25519 = {                ; COSE_Key
+PubKeyEd25519 = {                ; COSE_Key [RFC9052 s7]
     1 : 1,                       ; Key type : octet key pair
     3 : AlgorithmEdDSA,          ; Algorithm : EdDSA
     -1 : 6,                      ; Curve : Ed25519
     -2 : bstr                    ; X coordinate, little-endian
 }
 
-PubKeyECDSA256 = {               ; COSE_Key
+PubKeyECDSA256 = {               ; COSE_Key [RFC9052 s7]
     1 : 2,                       ; Key type : EC2
     3 : AlgorithmES256,          ; Algorithm : ECDSA w/ SHA-256
     -1 : 1,                      ; Curve: P256
@@ -150,14 +151,17 @@
     -3 : bstr                    ; Y coordinate, big-endian
 }
 
-PubKeyECDSA384 = {               ; COSE_Key
+PubKeyECDSA384 = {               ; COSE_Key [RFC9052 s7]
     1 : 2,                       ; Key type : EC2
     3 : AlgorithmES384,          ; Algorithm : ECDSA w/ SHA-384
     -1 : 2,                      ; Curve: P384
-    -2 : bstr,                   ; X coordinate
-    -3 : bstr                    ; Y coordinate
+    -2 : bstr,                   ; X coordinate, big-endian
+    -3 : bstr                    ; Y coordinate, big-endian
 }
 
-AlgorithmES256 = -7
-AlgorithmES384 = -35
-AlgorithmEdDSA = -8
+AlgorithmES256 = -7              ; [RFC9053 s2.1]
+AlgorithmES384 = -35             ; [RFC9053 s2.1]
+AlgorithmEdDSA = -8              ; [RFC9053 s2.2]
+
+; INCLUDE PublicKey.cddl for: PublicKey
+; INCLUDE DeviceInfoV3.cddl for: DeviceInfo
diff --git a/security/sharedsecret/aidl/vts/functional/SharedSecretAidlTest.cpp b/security/sharedsecret/aidl/vts/functional/SharedSecretAidlTest.cpp
index 51938ba..7599bce 100644
--- a/security/sharedsecret/aidl/vts/functional/SharedSecretAidlTest.cpp
+++ b/security/sharedsecret/aidl/vts/functional/SharedSecretAidlTest.cpp
@@ -164,7 +164,7 @@
     auto nonces = copyNonces(params);
     EXPECT_EQ(sharedSecrets.size(), nonces.size());
     std::sort(nonces.begin(), nonces.end());
-    std::unique(nonces.begin(), nonces.end());
+    nonces.erase(std::unique(nonces.begin(), nonces.end()), nonces.end());
     EXPECT_EQ(sharedSecrets.size(), nonces.size());
 
     auto responses = computeAllSharedSecrets(params);
diff --git a/sensors/aidl/default/Android.bp b/sensors/aidl/default/Android.bp
index 16b4d35..384ee97 100644
--- a/sensors/aidl/default/Android.bp
+++ b/sensors/aidl/default/Android.bp
@@ -28,9 +28,11 @@
     srcs: ["sensors-default.rc"],
 }
 
-filegroup {
+prebuilt_etc {
     name: "sensors-default.xml",
-    srcs: ["sensors-default.xml"],
+    src: "sensors-default.xml",
+    sub_dir: "vintf",
+    installable: false,
 }
 
 cc_library_static {
diff --git a/sensors/aidl/default/apex/Android.bp b/sensors/aidl/default/apex/Android.bp
index ceb428b..5482086 100644
--- a/sensors/aidl/default/apex/Android.bp
+++ b/sensors/aidl/default/apex/Android.bp
@@ -2,17 +2,6 @@
     default_applicable_licenses: ["hardware_interfaces_license"],
 }
 
-apex_key {
-    name: "com.android.hardware.sensors.key",
-    public_key: "com.android.hardware.sensors.avbpubkey",
-    private_key: "com.android.hardware.sensors.pem",
-}
-
-android_app_certificate {
-    name: "com.android.hardware.sensors.certificate",
-    certificate: "com.android.hardware.sensors",
-}
-
 genrule {
     name: "com.android.hardware.sensors.rc-gen",
     srcs: [":sensors-default.rc"],
@@ -31,16 +20,16 @@
 apex {
     name: "com.android.hardware.sensors",
     manifest: "apex_manifest.json",
-    key: "com.android.hardware.sensors.key",
-    certificate: ":com.android.hardware.sensors.certificate",
+    key: "com.android.hardware.key",
+    certificate: ":com.android.hardware.certificate",
     file_contexts: "file_contexts",
-    use_vndk_as_stable: true,
     updatable: false,
-    // Install the apex in /vendor/apex
-    soc_specific: true,
+    vendor: true,
+
     binaries: ["android.hardware.sensors-service.example"],
     prebuilts: [
-        "com.android.hardware.sensors.rc",
+        "com.android.hardware.sensors.rc", // init rc
+        "sensors-default.xml", // vintf fragment
         "android.hardware.sensor.ambient_temperature.prebuilt.xml",
         "android.hardware.sensor.barometer.prebuilt.xml",
         "android.hardware.sensor.gyroscope.prebuilt.xml",
@@ -49,5 +38,4 @@
         "android.hardware.sensor.proximity.prebuilt.xml",
         "android.hardware.sensor.relative_humidity.prebuilt.xml",
     ],
-    vintf_fragments: [":sensors-default.xml"],
 }
diff --git a/sensors/aidl/default/apex/file_contexts b/sensors/aidl/default/apex/file_contexts
index 27be16b..6d231f8 100644
--- a/sensors/aidl/default/apex/file_contexts
+++ b/sensors/aidl/default/apex/file_contexts
@@ -1,5 +1,3 @@
-(/.*)?							u:object_r:vendor_file:s0
-# Permission XMLs
-/etc/permissions(/.*)?					u:object_r:vendor_configs_file:s0
-# Service binary
-/bin/hw/android\.hardware\.sensors-service\.example	u:object_r:hal_sensors_default_exec:s0
\ No newline at end of file
+(/.*)?                                                u:object_r:vendor_file:s0
+/etc(/.*)?                                            u:object_r:vendor_configs_file:s0
+/bin/hw/android\.hardware\.sensors-service\.example   u:object_r:hal_sensors_default_exec:s0
\ No newline at end of file
diff --git a/soundtrigger/2.0/default/OWNERS b/soundtrigger/2.0/default/OWNERS
deleted file mode 100644
index ed739cf..0000000
--- a/soundtrigger/2.0/default/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-elaurent@google.com
-mnaganov@google.com
-ytai@google.com
diff --git a/soundtrigger/2.0/vts/functional/OWNERS b/soundtrigger/2.0/vts/functional/OWNERS
deleted file mode 100644
index 3c24468..0000000
--- a/soundtrigger/2.0/vts/functional/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-# Bug component: 48436
-elaurent@google.com
-mdooley@google.com
-ytai@google.com
diff --git a/soundtrigger/2.1/vts/functional/OWNERS b/soundtrigger/2.1/vts/functional/OWNERS
deleted file mode 100644
index 3c24468..0000000
--- a/soundtrigger/2.1/vts/functional/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-# Bug component: 48436
-elaurent@google.com
-mdooley@google.com
-ytai@google.com
diff --git a/soundtrigger/2.2/vts/functional/OWNERS b/soundtrigger/2.2/vts/functional/OWNERS
deleted file mode 100644
index 43126f6..0000000
--- a/soundtrigger/2.2/vts/functional/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-# Bug component: 48436
-ytai@google.com
-mdooley@google.com
diff --git a/soundtrigger/2.3/cli/OWNERS b/soundtrigger/2.3/cli/OWNERS
deleted file mode 100644
index 4fd27f3..0000000
--- a/soundtrigger/2.3/cli/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-include platform/frameworks/base:/services/core/java/com/android/server/soundtrigger_middleware/OWNERS
diff --git a/soundtrigger/2.3/vts/functional/OWNERS b/soundtrigger/2.3/vts/functional/OWNERS
deleted file mode 100644
index 3c24468..0000000
--- a/soundtrigger/2.3/vts/functional/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-# Bug component: 48436
-elaurent@google.com
-mdooley@google.com
-ytai@google.com
diff --git a/soundtrigger/OWNERS b/soundtrigger/OWNERS
new file mode 100644
index 0000000..3b35d27
--- /dev/null
+++ b/soundtrigger/OWNERS
@@ -0,0 +1,8 @@
+# Bug component: 48436
+
+include platform/frameworks/base:/media/aidl/android/media/soundtrigger_middleware/OWNERS
+include platform/frameworks/base:/services/core/java/com/android/server/soundtrigger_middleware/OWNERS
+
+elaurent@google.com
+mdooley@google.com
+mnaganov@google.com
diff --git a/soundtrigger/aidl/cli/OWNERS b/soundtrigger/aidl/cli/OWNERS
deleted file mode 100644
index 9f87c4c..0000000
--- a/soundtrigger/aidl/cli/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-include platform/frameworks/base:/media/aidl/android/media/soundtrigger_middleware/OWNERS
diff --git a/soundtrigger/aidl/cli/java/android/hardware/soundtrigger3/cli/SthalCli.java b/soundtrigger/aidl/cli/java/android/hardware/soundtrigger3/cli/SthalCli.java
index 127f062..41e2533 100644
--- a/soundtrigger/aidl/cli/java/android/hardware/soundtrigger3/cli/SthalCli.java
+++ b/soundtrigger/aidl/cli/java/android/hardware/soundtrigger3/cli/SthalCli.java
@@ -289,6 +289,8 @@
             Properties properties = new Properties();
             properties.implementor = "Android";
             properties.description = "Mock STHAL";
+            properties.uuid = "a5af2d2a-4cc4-4b69-a22f-c9d5b6d492c3";
+            properties.supportedModelArch = "Mock arch";
             properties.maxSoundModels = 2;
             properties.maxKeyPhrases = 1;
             properties.recognitionModes =
diff --git a/staging/OWNERS b/staging/OWNERS
new file mode 100644
index 0000000..a07824e
--- /dev/null
+++ b/staging/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 298954331
+
+include platform/hardware/interfaces:/OWNERS
diff --git a/tests/OWNERS b/tests/OWNERS
new file mode 100644
index 0000000..a07824e
--- /dev/null
+++ b/tests/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 298954331
+
+include platform/hardware/interfaces:/OWNERS
diff --git a/tetheroffload/OWNERS b/tetheroffload/OWNERS
new file mode 100644
index 0000000..e033269
--- /dev/null
+++ b/tetheroffload/OWNERS
@@ -0,0 +1,5 @@
+# Bug component: 261923493
+
+include platform/packages/modules/Connectivity:/Tethering/OWNERS
+
+kenghua@google.com
diff --git a/tetheroffload/aidl/default/Android.bp b/tetheroffload/aidl/default/Android.bp
index 8f0739c..8c96990 100644
--- a/tetheroffload/aidl/default/Android.bp
+++ b/tetheroffload/aidl/default/Android.bp
@@ -19,18 +19,52 @@
 cc_binary {
     name: "android.hardware.tetheroffload-service.example",
     relative_install_path: "hw",
-    init_rc: ["tetheroffload-example.rc"],
-    vintf_fragments: ["tetheroffload-example.xml"],
     vendor: true,
-    shared_libs: [
+
+    stl: "c++_static",
+    static_libs: [
         "android.hardware.tetheroffload-V1-ndk",
         "libbase",
+    ],
+    shared_libs: [
         "libbinder_ndk",
-        "libcutils",
-        "libutils",
+        "liblog",
     ],
     srcs: [
         "main.cpp",
         "Offload.cpp",
     ],
+
+    installable: false, // installed in APEX
+}
+
+prebuilt_etc {
+    name: "tetheroffload-example.rc",
+    src: "tetheroffload-example.rc",
+    installable: false,
+}
+
+prebuilt_etc {
+    name: "tetheroffload-example.xml",
+    src: "tetheroffload-example.xml",
+    sub_dir: "vintf",
+    installable: false,
+}
+
+apex {
+    name: "com.android.hardware.tetheroffload",
+    manifest: "apex_manifest.json",
+    file_contexts: "apex_file_contexts",
+    key: "com.android.hardware.key",
+    certificate: ":com.android.hardware.certificate",
+    updatable: false,
+    vendor: true,
+
+    binaries: [
+        "android.hardware.tetheroffload-service.example",
+    ],
+    prebuilts: [
+        "tetheroffload-example.rc",
+        "tetheroffload-example.xml",
+    ],
 }
diff --git a/tetheroffload/aidl/default/apex_file_contexts b/tetheroffload/aidl/default/apex_file_contexts
new file mode 100644
index 0000000..a520101
--- /dev/null
+++ b/tetheroffload/aidl/default/apex_file_contexts
@@ -0,0 +1,3 @@
+(/.*)?                                                          u:object_r:vendor_file:s0
+/etc(/.*)?                                                      u:object_r:vendor_configs_file:s0
+/bin/hw/android\.hardware\.tetheroffload-service\.example       u:object_r:hal_tetheroffload_default_exec:s0
diff --git a/tetheroffload/aidl/default/apex_manifest.json b/tetheroffload/aidl/default/apex_manifest.json
new file mode 100644
index 0000000..4c90889
--- /dev/null
+++ b/tetheroffload/aidl/default/apex_manifest.json
@@ -0,0 +1,4 @@
+{
+    "name": "com.android.hardware.tetheroffload",
+    "version": 1
+}
diff --git a/tetheroffload/aidl/default/tetheroffload-example.rc b/tetheroffload/aidl/default/tetheroffload-example.rc
index 46cda61..b95544b 100644
--- a/tetheroffload/aidl/default/tetheroffload-example.rc
+++ b/tetheroffload/aidl/default/tetheroffload-example.rc
@@ -1,4 +1,4 @@
-service vendor.tetheroffload-example /vendor/bin/hw/android.hardware.tetheroffload-service.example
+service vendor.tetheroffload-example /apex/com.android.hardware.tetheroffload/bin/hw/android.hardware.tetheroffload-service.example
     class hal
     user nobody
     group nobody
diff --git a/thermal/aidl/default/Android.bp b/thermal/aidl/default/Android.bp
index 49a578b..451e1e2 100644
--- a/thermal/aidl/default/Android.bp
+++ b/thermal/aidl/default/Android.bp
@@ -24,26 +24,50 @@
 cc_binary {
     name: "android.hardware.thermal-service.example",
     relative_install_path: "hw",
-    init_rc: [":android.hardware.thermal.example.rc"],
-    vintf_fragments: [":android.hardware.thermal.example.xml"],
     vendor: true,
-    shared_libs: [
-        "libbase",
-        "libbinder_ndk",
+    stl: "c++_static",
+    static_libs: [
         "android.hardware.thermal-V1-ndk",
+        "libbase",
+    ],
+    shared_libs: [
+        "libbinder_ndk",
+        "liblog",
     ],
     srcs: [
         "main.cpp",
         "Thermal.cpp",
     ],
+    installable: false,
 }
 
-filegroup {
+prebuilt_etc {
     name: "android.hardware.thermal.example.xml",
-    srcs: ["thermal-example.xml"],
+    src: "thermal-example.xml",
+    sub_dir: "vintf",
+    installable: false,
 }
 
-filegroup {
+prebuilt_etc {
     name: "android.hardware.thermal.example.rc",
-    srcs: ["thermal-example.rc"],
+    src: "thermal-example.rc",
+    installable: false,
+}
+
+apex {
+    name: "com.android.hardware.thermal",
+    manifest: "apex_manifest.json",
+    file_contexts: "apex_file_contexts",
+    key: "com.android.hardware.key",
+    certificate: ":com.android.hardware.certificate",
+    updatable: false,
+    vendor: true,
+
+    binaries: [
+        "android.hardware.thermal-service.example",
+    ],
+    prebuilts: [
+        "android.hardware.thermal.example.xml",
+        "android.hardware.thermal.example.rc",
+    ],
 }
diff --git a/thermal/aidl/default/apex_file_contexts b/thermal/aidl/default/apex_file_contexts
new file mode 100644
index 0000000..9fa5339
--- /dev/null
+++ b/thermal/aidl/default/apex_file_contexts
@@ -0,0 +1,3 @@
+(/.*)?                                                          u:object_r:vendor_file:s0
+/etc(/.*)?                                                      u:object_r:vendor_configs_file:s0
+/bin/hw/android\.hardware\.thermal-service\.example             u:object_r:hal_thermal_default_exec:s0
diff --git a/thermal/aidl/default/apex_manifest.json b/thermal/aidl/default/apex_manifest.json
new file mode 100644
index 0000000..80420d5
--- /dev/null
+++ b/thermal/aidl/default/apex_manifest.json
@@ -0,0 +1,4 @@
+{
+    "name": "com.android.hardware.thermal",
+    "version": 1
+}
diff --git a/thermal/aidl/default/thermal-example.rc b/thermal/aidl/default/thermal-example.rc
index 591ca03..36dde0d 100644
--- a/thermal/aidl/default/thermal-example.rc
+++ b/thermal/aidl/default/thermal-example.rc
@@ -1,4 +1,4 @@
-service vendor.thermal-example /vendor/bin/hw/android.hardware.thermal-service.example
+service vendor.thermal-example /apex/com.android.hardware.thermal/bin/hw/android.hardware.thermal-service.example
     class hal
     user nobody
     group system
diff --git a/threadnetwork/aidl/default/Android.bp b/threadnetwork/aidl/default/Android.bp
index 62c8c9e..816f892 100644
--- a/threadnetwork/aidl/default/Android.bp
+++ b/threadnetwork/aidl/default/Android.bp
@@ -83,8 +83,8 @@
 }
 
 prebuilt_etc {
-    name: "threadnetwork-service-sim.rc",
-    src: "threadnetwork-service-sim.rc",
+    name: "threadnetwork-service.rc",
+    src: "threadnetwork-service.rc",
     installable: false,
 }
 
@@ -101,9 +101,10 @@
         "android.hardware.threadnetwork-service",
         "ot-rcp",
     ],
+
     prebuilts: [
         "threadnetwork-default.xml", // vintf_fragment
-        "threadnetwork-service-sim.rc", // init_rc
+        "threadnetwork-service.rc", // init_rc
         "android.hardware.thread_network.prebuilt.xml", // permission
     ],
 }
diff --git a/threadnetwork/aidl/default/threadnetwork-service-sim.rc b/threadnetwork/aidl/default/threadnetwork-service.rc
similarity index 100%
rename from threadnetwork/aidl/default/threadnetwork-service-sim.rc
rename to threadnetwork/aidl/default/threadnetwork-service.rc
diff --git a/tv/OWNERS b/tv/OWNERS
new file mode 100644
index 0000000..e051b28
--- /dev/null
+++ b/tv/OWNERS
@@ -0,0 +1,13 @@
+# TV tuner
+# Bug component: 136752
+# TV input
+# Bug component: 826094
+
+include platform/frameworks/base:/core/java/android/hardware/hdmi/OWNERS
+
+hgchen@google.com
+quxiangfang@google.com
+shubang@google.com
+yixiaoluo@google.com
+qingxun@google.com
+
diff --git a/tv/cec/1.0/default/OWNERS b/tv/cec/1.0/default/OWNERS
deleted file mode 100644
index c1d3f1d..0000000
--- a/tv/cec/1.0/default/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-include platform/frameworks/base:/core/java/android/hardware/hdmi/OWNERS
diff --git a/tv/cec/OWNERS b/tv/cec/OWNERS
deleted file mode 100644
index 71e74c0..0000000
--- a/tv/cec/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 826094
-include platform/frameworks/base:/core/java/android/hardware/hdmi/OWNERS
diff --git a/tv/hdmi/OWNERS b/tv/hdmi/OWNERS
deleted file mode 100644
index d9c6783..0000000
--- a/tv/hdmi/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 826094
-include platform/frameworks/base:/core/java/android/hardware/hdmi/OWNERS
\ No newline at end of file
diff --git a/tv/input/OWNERS b/tv/input/OWNERS
index ae65f67..1252e4e 100644
--- a/tv/input/OWNERS
+++ b/tv/input/OWNERS
@@ -1,5 +1 @@
-# Bug component: 105688
-hgchen@google.com
-shubang@google.com
-quxiangfang@google.com
-yixiaoluo@google.com
+# Bug component: 826094
diff --git a/tv/tuner/1.0/default/OWNERS b/tv/tuner/1.0/default/OWNERS
deleted file mode 100644
index 1b3d095..0000000
--- a/tv/tuner/1.0/default/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-nchalko@google.com
-amyjojo@google.com
-shubang@google.com
-quxiangfang@google.com
diff --git a/tv/tuner/1.0/vts/OWNERS b/tv/tuner/1.0/vts/OWNERS
deleted file mode 100644
index 9bdafca..0000000
--- a/tv/tuner/1.0/vts/OWNERS
+++ /dev/null
@@ -1,5 +0,0 @@
-# Bug component: 136752
-nchalko@google.com
-amyjojo@google.com
-shubang@google.com
-quxiangfang@google.com
diff --git a/tv/tuner/1.1/default/OWNERS b/tv/tuner/1.1/default/OWNERS
deleted file mode 100644
index 1b3d095..0000000
--- a/tv/tuner/1.1/default/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-nchalko@google.com
-amyjojo@google.com
-shubang@google.com
-quxiangfang@google.com
diff --git a/tv/tuner/1.1/vts/OWNERS b/tv/tuner/1.1/vts/OWNERS
deleted file mode 100644
index 9bdafca..0000000
--- a/tv/tuner/1.1/vts/OWNERS
+++ /dev/null
@@ -1,5 +0,0 @@
-# Bug component: 136752
-nchalko@google.com
-amyjojo@google.com
-shubang@google.com
-quxiangfang@google.com
diff --git a/tv/tuner/aidl/default/OWNERS b/tv/tuner/aidl/default/OWNERS
deleted file mode 100644
index bf2b609..0000000
--- a/tv/tuner/aidl/default/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-hgchen@google.com
-shubang@google.com
-quxiangfang@google.com
diff --git a/tv/tuner/aidl/vts/OWNERS b/tv/tuner/aidl/vts/OWNERS
deleted file mode 100644
index 5b33bf2..0000000
--- a/tv/tuner/aidl/vts/OWNERS
+++ /dev/null
@@ -1,5 +0,0 @@
-# Bug component: 136752
-
-hgchen@google.com
-shubang@google.com
-quxiangfang@google.com
diff --git a/tv/tuner/config/OWNERS b/tv/tuner/config/OWNERS
deleted file mode 100644
index bf2b609..0000000
--- a/tv/tuner/config/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-hgchen@google.com
-shubang@google.com
-quxiangfang@google.com
diff --git a/uwb/aidl/default/Android.bp b/uwb/aidl/default/Android.bp
index c6d1a52..f9b79de 100644
--- a/uwb/aidl/default/Android.bp
+++ b/uwb/aidl/default/Android.bp
@@ -15,11 +15,13 @@
     prefer_rlib: true,
     rustlibs: [
         "android.hardware.uwb-V1-rust",
+        "liblibc",
         "liblogger",
         "liblog_rust",
         "libbinder_rs",
         "libbinder_tokio_rs",
         "libtokio",
+        "libtokio_util",
         "libnix",
         "libanyhow",
     ],
@@ -46,23 +48,12 @@
     installable: false,
 }
 
-apex_key {
-    name: "com.android.hardware.uwb.key",
-    public_key: "com.android.hardware.uwb.avbpubkey",
-    private_key: "com.android.hardware.uwb.pem",
-}
-
-android_app_certificate {
-    name: "com.android.hardware.uwb.certificate",
-    certificate: "com.android.hardware.uwb",
-}
-
 apex {
     name: "com.android.hardware.uwb",
     manifest: "manifest.json",
     file_contexts: "file_contexts",
-    key: "com.android.hardware.uwb.key",
-    certificate: ":com.android.hardware.uwb.certificate",
+    key: "com.android.hardware.key",
+    certificate: ":com.android.hardware.certificate",
     updatable: false,
     vendor: true,
 
diff --git a/uwb/aidl/default/com.android.hardware.uwb.avbpubkey b/uwb/aidl/default/com.android.hardware.uwb.avbpubkey
deleted file mode 100644
index 7a7fce8..0000000
--- a/uwb/aidl/default/com.android.hardware.uwb.avbpubkey
+++ /dev/null
Binary files differ
diff --git a/uwb/aidl/default/com.android.hardware.uwb.pem b/uwb/aidl/default/com.android.hardware.uwb.pem
deleted file mode 100644
index cd38ef8..0000000
--- a/uwb/aidl/default/com.android.hardware.uwb.pem
+++ /dev/null
@@ -1,52 +0,0 @@
------BEGIN PRIVATE KEY-----
-MIIJRAIBADANBgkqhkiG9w0BAQEFAASCCS4wggkqAgEAAoICAQChE5EVDbSAKAru
-myK22LP72i2ivpJGi8DqRjgA5r6Zz3OKwtvrtSBaTtACv3j6ZALLndA2sgxbt64B
-ik1vU1tpnrGnaqcdlgDio6QIfpavWEcZ9rOHuGXvLlv3Tzc2gyr1UKsaGtce+os8
-jbfyEl4keN59oI2D8Nj1VVKYRKS+mrp4+hnvt3itGbvIKLCgGBYlcSxIiWKDfJXy
-jQEpb5pZy3wCdn2CCrTb64oclkmYbGcfoYuSBV6+PBrGa2b0b5aWm40YFbgZ5h+j
-Hlkb7sX7Vz499DK1lbm8rRt+EkHZ/9IFS1DBSj6MK3LKyGspj7BzJ25UQI23B3pM
-iaNsjBR1gGwqJxWpjuuZm9qdNPMSUUSxs/EB0GX96jnC5HFjh3sLOWKqqP6SRCZW
-xYRzjAno1L1jjPXdDqM9n2aJHu35+YVG/sFn20eIBSxH9u1hSnOw8ccc0Zo774cc
-oTJHKlL9GUO5SEGLkz3XTMEe6e55yujChymMe5jz8jkkCaXqsNDB0AMUtQ6g0Kzu
-FNUdTS2DAr/Xo7qxJ6VoDwOx/OQeDQSjSuojt/JMHEp6QMir+/axVWuxIaegjElH
-Kmx7Ie6ZGZscaTxKFEYEkWaIeJKTml0NxEitrJAibc58itj93zBMP2EDve46ghWJ
-SlmeeVmn0CuYeE8EHwZSB4I7EaHP1QIDAQABAoICADQESZnu7xdj1wPu/Wrm2FjA
-wHQJ7trxTr9ZJcTEv1CUec+Z1cNsnqILSYlZpAvYOD7hG9hN70e/LWY573+//4lA
-Qka6XnVjd625AsPrfWXqsCtmS9vMZL60zeYzorTr7veBsX+go0/RwR0w9vIplFVa
-4x7Wtlyhbq7retzJbhpPhWCEA9Qx/7qG0Ol2mnNY0+4Lei2CkFm95f6KIpHrBIFz
-AP0anrVcF8PdcKCCuAmNGFBSruvc6Beu+UaScJEHaC4C1bGtceKLOjRHHKe0mCLu
-rZ78OVQCohSYIoS4CKQJxR0IkW+aNlC1x0BNMK4fRPArD6oNnrY4p/oHiMsJAaHc
-tLWeUqvlSAdK0C5ejUzdjTiZW7rzI2gluy+BBKY1nByQsVWK7saG6hEON63idfl+
-GwPPb253n49UIk3UlUy1PxVb/othlw0dlD7p4wAlOJoRlOuJnqAifwWckS2rpNHO
-9wR1tak8hLi2LMDJqu/GlHoSqkb+JdAV5yujLQ8k1So/y/4bvNY2pRpXPydxkOew
-FY/BOoslS6RD5/XHfSJsK/Oq53Y+d04qdV7jwgrp4lqFEqMwJgzVEoC5cMvJVeK9
-/wjUdWw9hg0DSk8LVmNbIWZjZs4C39uQljmt8s+exSmzm5MSQU3K11vGRGKOsPlA
-5ZzRRaV81lBYKhATE8aRAoIBAQDfPgJ3l/38RPyoNrJuhOPH4UJj0rDX0+5ezqla
-iAXDxec55lM8qbPDW3jl/MWE3LePVokKN8DBxwZxi9Po4UEQ4hG4+zIyPcT1AQlH
-+kHGG0TBtJox8J+DkG5oW79wXCn6tyl8ZLwWNa6T/3vIi3BNadnoe3AFqgcHVwHz
-e/tl0z6Tz56r/eNN6dl01+D31rirqiYRbe3982ZiX3JfS3t+AIQoxcU4suU+DC37
-G5h0zbzjgXP+ZrpPfh6O7JwH7Ac83nJAYBsVcHU4P/ZstkIWjuzleEQcDcsj3sHu
-NO2/wbReo/8Yvk0q2vUQm9IkWlU83H2KLPzIa1VuzTfPql0bAoIBAQC4tlP393ly
-krhmRLs6msAjXp5oZzoyHnrYvn+5LlKoPul98EqAW9GczLSlgjYO3w2DqnimBhU/
-YorWvkhcSJsrjiEn7CZ3UXuXoLciRiyHk/3xSDP4CLZ8tvUcEGs34LITXMPlrIk1
-WfYseSukE1TB6GDEj4MsxFILKhwnxGWeD9x9+ejOPj7+Jk3oTiZPVc67LR0MDgDz
-hRZW/8VOsequ+B/TF9LiwUHI3Ps3Geh3kKMR6DQaxXW08HDk1NGsZmKXq+O+JWFT
-3ZwCNnXqUCpm9YsD6QXTHILtBHVS5cxE65BFs08WEAqcgDhr3Yczz8L/UN/qR+FH
-RSOcymVFHQXPAoIBAQDK8Lsbbw+UGj64yGhysdnD5dINnwXmXiHPC/3Gb+sVqr3l
-060Nc5QYXvpL0PraKi+wXVFc+YwAXGZOKHfut38H0wubZreeFqsKsvN1/Fl4t2dM
-1FpsVbscxdqogedJRG9hHMrY61ZUtl5K6jDkAWaI6VYP0s7mR0f2czEx4B6M1XmI
-s3AiGD5foNtvLaS0iPz+CUJsC8wTVQZZHT2CxcKwq9V4nzkHrxFY04elQ9PXMwSo
-qRECTu7FvvgWo5/AT9/QhMPGI9fbKI1XIkZpU1JG4Y0XmboI6r0lkaYoXvNWo8fN
-VTZcjvrln4CypYRmSbw9BJAXYYg2xeQ3QtWesdfLAoIBAQCM9ifyjpvSQgITmdRA
-jySeWXEOP+j7oqMhkY+rZJyT5R8Pizdv6aJ3xQj/XfWfN736gzf7i5zfeHZ4F1Ll
-iktQ2/CVpPReDoMBXhckQuVsuhYL8owmd4+8cWtw9V69j+6WNC8Tsa4sVvE1U2to
-lZATQyHGH7d9jH0IJCTEfG8IRxZ/1R5DduFf1x+Rb0JxPQy9b1pBftZfAWvhDOQo
-gEKXMKgo0n+PqOhpP6s/i7gKtwibe9d3rsV7RhsBpyA0LxaCpRzyWViDRhXu4lzu
-aitR04U5gLV/PLz14Hcgwlo3JoY9iu+J6MgQUxG7z52EfsNTUQbwpdZYK31YBGVw
-bwulAoIBAQClsNAtbbwmExh3P0rjkgQOVy7FMQXgOyldR/LYTRI6Zbt47Jb4eO6M
-vfKK4C67/RoD1PEWgdboY8axPNj3dR1RdAuyTOOJfhJYVCW2eRS2fjSjYmUnLoFB
-N2ABYE8yKmmcPIlcJzXs3Jzeb+URxtDrvuEWPBHm8Ia1u29t42W7pg4AZHitilTl
-Su1Xi+Ic2n0NVzqZzLVUb6dKr2NFAjynthOCFXbbwD6awFeTxFIXVGT9TPTaiIlA
-Ssnh+yii4NHRoZjivUCsrfEfn+NiCzOgrfXTtUiRDvhZHdpqAIqQ6lpju7naCCwG
-vApJsLERxjCi0eqDwVx/e6xbeOVUZc/m
------END PRIVATE KEY-----
diff --git a/uwb/aidl/default/com.android.hardware.uwb.pk8 b/uwb/aidl/default/com.android.hardware.uwb.pk8
deleted file mode 100644
index 8855197..0000000
--- a/uwb/aidl/default/com.android.hardware.uwb.pk8
+++ /dev/null
Binary files differ
diff --git a/uwb/aidl/default/com.android.hardware.uwb.x509.pem b/uwb/aidl/default/com.android.hardware.uwb.x509.pem
deleted file mode 100644
index 762ad88..0000000
--- a/uwb/aidl/default/com.android.hardware.uwb.x509.pem
+++ /dev/null
@@ -1,34 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIF1TCCA70CFEagTJLwbnblSQu8MjFHXcEDFQ1MMA0GCSqGSIb3DQEBCwUAMIGl
-MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91
-bnRhaW4gVmlldzEQMA4GA1UECgwHQW5kcm9pZDEQMA4GA1UECwwHQW5kcm9pZDEi
-MCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTEhMB8GA1UEAwwYY29t
-LmFuZHJvaWQuaGFyZHdhcmUudXdiMCAXDTIzMDgyMTA0MTE0M1oYDzQ3NjEwNzE3
-MDQxMTQzWjCBpTELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAU
-BgNVBAcMDU1vdW50YWluIFZpZXcxEDAOBgNVBAoMB0FuZHJvaWQxEDAOBgNVBAsM
-B0FuZHJvaWQxIjAgBgkqhkiG9w0BCQEWE2FuZHJvaWRAYW5kcm9pZC5jb20xITAf
-BgNVBAMMGGNvbS5hbmRyb2lkLmhhcmR3YXJlLnV3YjCCAiIwDQYJKoZIhvcNAQEB
-BQADggIPADCCAgoCggIBAJpvvE7i50v4hE5VmlFTiOsQ+zOYWF+MjzEMXcqLQDzs
-26XBYJV7O3TwgrQNp1XV8KCPTAF8APEyGb237rlZO/3KvS9zYa3zFfEMPg5pnFmR
-QLWSfqrXm7ttKIQHNVAjqrLnlt8pjvKS/t/UXLAWgHiXnd2ZX62tQjyDouszLEwP
-59zJbkgX9o6fwEssdRTpuyoRoyPylfK3Thk22RBSTt+pS6pwqeUj4vttrPr7k7YU
-S5CeB7XVBRPRzXFrpasgzQqp2deOpqxC44H90+pl7QmBHFrnGk+90lcOPYgqF2Ah
-DfCBxAHzn8ioSsAJ0U34yqoNbWIUX3ZHgq1ru1uctdLwGMrKmqsw4uvfXLV+sjoi
-qUFW+9uEOHAVnmZEO2T7LAlUIoAGgdd58EJ+hdXP2yvNpGVPestrwWttAaMJoEJN
-qEWt67+iEjdEpVn0lUFo+up42mYEXGUAOpoc6t5WJinrQTY4JK/OIGJPUiOjbUTI
-T/hQTddr0HNGsKP2zRv0d49VtVht6wR0HlO1srCFZAGxRIdBtjjenu1l7ALMWlHw
-4YXLSpQoeYfavV8C3j5bzz6KaDj6HcKvRbyHRX8+JL9kFDgpOD1yI/jaaPepRAe6
-qek5jEJMEFj0tFifB8e0CZbURreXa1tErWybfuDkaNBDtAHL333/IQGI0vV7zr0x
-AgMBAAEwDQYJKoZIhvcNAQELBQADggIBAFqnBngYd7rXHwIXHYKZuRMf+NLQxNFN
-f0m6ioFYgNnMwoMQidBHdRsJ2qTb9zfyt5O1/5Wel8Ix9aUCRbJejyX2lYXNIJNC
-ykahkoP+3CEA8QtPkmtWzNraDJRh2eYn6V5DJOWyvkz02DsHA4mxatYkF7dUfqLx
-f/y1y3cbnTyAraotTRb3W/F/zEYbcCzwlFZDT/IASVM89WRDE76+rp7/wDNJ0aEJ
-l6cQaUWDPbrvDWZaptRWfnebPtg81v03qKauwrBADddxu+/Nqs0iczBdsP1tdXr/
-Hxs47D7+fZnytVQglldBG4yky9YceL22yft/bCNDe5d7nF1/iUpJNbRIcrZxD86Z
-wwPpo0VMJ+r6VuD6UGQTS6Zyi94QD3GYYkGrPPwyrLKpp1EU6dV32bWCNp5eQojY
-FyTse/lfAJ9/Xu3klHYuR9xOaJiH+2MmtJTwKdjvK5h+EIiVbyrDJJHBd9sWav3a
-Emo+wKaIxQzXEUjWxUwy7eAAwq5WzawLMMQ97P0zIgasNIlUHW2cvBzVsQlM1tN7
-2t+7UPs5RifK5hadK6Ge1oqkG0xC1t65E7yGwrPMzKuz9aPgg7j1YAaETcKuFOHG
-rZr/0kALZc6VKNSZ8eM2P5ObrelLOe4ED9Ha1ZhmnCDXN9BP2gwqmCekwfNJ3cPA
-GObJiF81f9ZM
------END CERTIFICATE-----
diff --git a/uwb/aidl/default/src/uwb_chip.rs b/uwb/aidl/default/src/uwb_chip.rs
index 9587efb..2b8e481 100644
--- a/uwb/aidl/default/src/uwb_chip.rs
+++ b/uwb/aidl/default/src/uwb_chip.rs
@@ -4,32 +4,34 @@
 };
 use android_hardware_uwb::binder;
 use async_trait::async_trait;
-use binder::{Result, Strong};
+use binder::{DeathRecipient, IBinder, Result, Strong};
 
-use tokio::fs::{File, OpenOptions};
-use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use std::sync::Arc;
+use tokio::io::unix::AsyncFd;
+use tokio::select;
 use tokio::sync::Mutex;
+use tokio_util::sync::CancellationToken;
 
+use std::fs::{File, OpenOptions};
+use std::io::{self, Read, Write};
 use std::os::fd::AsRawFd;
-
-use std::io;
-
-use nix::sys::termios;
+use std::os::unix::fs::OpenOptionsExt;
 
 enum State {
     Closed,
     Opened {
         callbacks: Strong<dyn IUwbClientCallback>,
-        #[allow(dead_code)]
-        tasks: tokio::task::JoinSet<()>,
+        handle: tokio::task::JoinHandle<()>,
         serial: File,
+        death_recipient: DeathRecipient,
+        token: CancellationToken,
     },
 }
 
 pub struct UwbChip {
     name: String,
     path: String,
-    state: Mutex<State>,
+    state: Arc<Mutex<State>>,
 }
 
 impl UwbChip {
@@ -37,23 +39,54 @@
         Self {
             name,
             path,
-            state: Mutex::new(State::Closed),
+            state: Arc::new(Mutex::new(State::Closed)),
         }
     }
 }
 
+impl State {
+    /// Terminate the reader task.
+    async fn close(&mut self) -> Result<()> {
+        if let State::Opened { ref mut token, ref callbacks, ref mut death_recipient, ref mut handle, .. } = *self {
+            log::info!("waiting for task cancellation");
+            callbacks.as_binder().unlink_to_death(death_recipient)?;
+            token.cancel();
+            handle.await.unwrap();
+            log::info!("task successfully cancelled");
+            callbacks.onHalEvent(UwbEvent::CLOSE_CPLT, UwbStatus::OK)?;
+            *self = State::Closed;
+        }
+        Ok(())
+    }
+}
+
 pub fn makeraw(file: File) -> io::Result<File> {
     let fd = file.as_raw_fd();
 
-    let mut attrs = termios::tcgetattr(fd)?;
-
-    termios::cfmakeraw(&mut attrs);
-
-    termios::tcsetattr(fd, termios::SetArg::TCSANOW, &attrs)?;
+    // Configure the file descritpro as raw fd.
+    use nix::sys::termios::*;
+    let mut attrs = tcgetattr(fd)?;
+    cfmakeraw(&mut attrs);
+    tcsetattr(fd, SetArg::TCSANOW, &attrs)?;
 
     Ok(file)
 }
 
+/// Wrapper around Read::read to handle EWOULDBLOCK.
+/// /!\ will actively wait for more data, make sure to call
+/// this method only when data is immediately expected.
+fn read_exact(file: &mut File, mut buf: &mut [u8]) -> io::Result<()> {
+    while buf.len() > 0 {
+        match file.read(buf) {
+            Ok(0) => panic!("unexpectedly reached end of file"),
+            Ok(read_len) => buf = &mut buf[read_len..],
+            Err(err) if err.kind() == io::ErrorKind::WouldBlock => continue,
+            Err(err) => return Err(err),
+        }
+    }
+    Ok(())
+}
+
 impl binder::Interface for UwbChip {}
 
 #[async_trait]
@@ -65,60 +98,113 @@
     async fn open(&self, callbacks: &Strong<dyn IUwbClientCallback>) -> Result<()> {
         log::debug!("open: {:?}", &self.path);
 
+        let mut state = self.state.lock().await;
+
+        if matches!(*state, State::Opened { .. }) {
+            log::error!("the state is already opened");
+            return Err(binder::ExceptionCode::ILLEGAL_STATE.into());
+        }
+
         let serial = OpenOptions::new()
             .read(true)
             .write(true)
             .create(false)
+            .custom_flags(libc::O_NONBLOCK)
             .open(&self.path)
-            .await
             .and_then(makeraw)
             .map_err(|_| binder::StatusCode::UNKNOWN_ERROR)?;
 
-        let mut state = self.state.lock().await;
+        let state_death_recipient = self.state.clone();
+        let mut death_recipient = DeathRecipient::new(move || {
+            let mut state = state_death_recipient.blocking_lock();
+            log::info!("Uwb service has died");
+            if let State::Opened { ref mut token, .. } = *state {
+                token.cancel();
+                *state = State::Closed;
+            }
+        });
 
-        if let State::Closed = *state {
-            let client_callbacks = callbacks.clone();
+        callbacks.as_binder().link_to_death(&mut death_recipient)?;
 
-            let mut tasks = tokio::task::JoinSet::new();
-            let mut reader = serial
-                .try_clone()
-                .await
-                .map_err(|_| binder::StatusCode::UNKNOWN_ERROR)?;
+        let token = CancellationToken::new();
+        let cloned_token = token.clone();
 
-            tasks.spawn(async move {
-                loop {
-                    const UWB_HEADER_SIZE: usize = 4;
+        let client_callbacks = callbacks.clone();
 
-                    let mut buffer = vec![0; UWB_HEADER_SIZE];
-                    reader
-                        .read_exact(&mut buffer[0..UWB_HEADER_SIZE])
-                        .await
-                        .unwrap();
+        let reader = serial
+            .try_clone()
+            .map_err(|_| binder::StatusCode::UNKNOWN_ERROR)?;
 
-                    let length = buffer[3] as usize + UWB_HEADER_SIZE;
+        let join_handle = tokio::task::spawn(async move {
+            log::info!("UCI reader task started");
+            let mut reader = AsyncFd::new(reader).unwrap();
 
-                    buffer.resize(length, 0);
-                    reader
-                        .read_exact(&mut buffer[UWB_HEADER_SIZE..length])
-                        .await
-                        .unwrap();
+            loop {
+                const UWB_HEADER_SIZE: usize = 4;
+                let mut buffer = vec![0; UWB_HEADER_SIZE];
 
-                    client_callbacks.onUciMessage(&buffer[..]).unwrap();
-                }
-            });
+                // The only time where the task can be safely
+                // cancelled is when no packet bytes have been read.
+                //
+                // - read_exact() cannot be used here since it is not
+                //   cancellation safe.
+                // - read() cannot be used because it cannot be cancelled:
+                //   the syscall is executed blocking on the threadpool
+                //   and completes after termination of the task when
+                //   the pipe receives more data.
+                let read_len = loop {
+                    // On some platforms, the readiness detecting mechanism
+                    // relies on edge-triggered notifications. This means that
+                    // the OS will only notify Tokio when the file descriptor
+                    // transitions from not-ready to ready. For this to work
+                    // you should first try to read or write and only poll for
+                    // readiness if that fails with an error of
+                    // std::io::ErrorKind::WouldBlock.
+                    match reader.get_mut().read(&mut buffer) {
+                        Ok(0) => {
+                            log::error!("file unexpectedly closed");
+                            return;
+                        }
+                        Ok(read_len) => break read_len,
+                        Err(err) if err.kind() == io::ErrorKind::WouldBlock => (),
+                        Err(_) => panic!("unexpected read failure"),
+                    }
 
-            callbacks.onHalEvent(UwbEvent::OPEN_CPLT, UwbStatus::OK)?;
+                    let mut guard = select! {
+                        _ = cloned_token.cancelled() => {
+                            log::info!("task is cancelled!");
+                            return;
+                        },
+                        result = reader.readable() => result.unwrap()
+                    };
 
-            *state = State::Opened {
-                callbacks: callbacks.clone(),
-                tasks,
-                serial,
-            };
+                    guard.clear_ready();
+                };
 
-            Ok(())
-        } else {
-            Err(binder::ExceptionCode::ILLEGAL_STATE.into())
-        }
+                // Read the remaining header bytes, if truncated.
+                read_exact(reader.get_mut(), &mut buffer[read_len..]).unwrap();
+
+                let length = buffer[3] as usize + UWB_HEADER_SIZE;
+                buffer.resize(length, 0);
+
+                // Read the payload bytes.
+                read_exact(reader.get_mut(), &mut buffer[UWB_HEADER_SIZE..]).unwrap();
+
+                client_callbacks.onUciMessage(&buffer).unwrap();
+            }
+        });
+
+        callbacks.onHalEvent(UwbEvent::OPEN_CPLT, UwbStatus::OK)?;
+
+        *state = State::Opened {
+            callbacks: callbacks.clone(),
+            handle: join_handle,
+            serial,
+            death_recipient,
+            token,
+        };
+
+        Ok(())
     }
 
     async fn close(&self) -> Result<()> {
@@ -126,10 +212,8 @@
 
         let mut state = self.state.lock().await;
 
-        if let State::Opened { ref callbacks, .. } = *state {
-            callbacks.onHalEvent(UwbEvent::CLOSE_CPLT, UwbStatus::OK)?;
-            *state = State::Closed;
-            Ok(())
+        if matches!(*state, State::Opened { .. }) {
+            state.close().await
         } else {
             Err(binder::ExceptionCode::ILLEGAL_STATE.into())
         }
@@ -162,7 +246,6 @@
         if let State::Opened { ref mut serial, .. } = &mut *self.state.lock().await {
             serial
                 .write(data)
-                .await
                 .map(|written| written as i32)
                 .map_err(|_| binder::StatusCode::UNKNOWN_ERROR.into())
         } else {
diff --git a/vr/OWNERS b/vr/OWNERS
new file mode 100644
index 0000000..a07824e
--- /dev/null
+++ b/vr/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 298954331
+
+include platform/hardware/interfaces:/OWNERS
diff --git a/weaver/aidl/android/hardware/weaver/IWeaver.aidl b/weaver/aidl/android/hardware/weaver/IWeaver.aidl
index ae816ef..30168e3 100644
--- a/weaver/aidl/android/hardware/weaver/IWeaver.aidl
+++ b/weaver/aidl/android/hardware/weaver/IWeaver.aidl
@@ -58,7 +58,9 @@
      * Throttling must be used to limit the frequency of failed read attempts.
      * The value is only returned when throttling is not active, even if the
      * correct key is provided. If called when throttling is active, the time
-     * until the next attempt can be made is returned.
+     * until the next attempt can be made is returned. Throttling must be
+     * applied on a per-slot basis so that a successful read from one slot does
+     * not reset the throttling state of any other slot.
      *
      * Service status return:
      *
diff --git a/wifi/1.0/vts/functional/wifi_hidl_test_utils.cpp b/wifi/1.0/vts/functional/wifi_hidl_test_utils.cpp
index 02f8209..fae30c0 100644
--- a/wifi/1.0/vts/functional/wifi_hidl_test_utils.cpp
+++ b/wifi/1.0/vts/functional/wifi_hidl_test_utils.cpp
@@ -89,6 +89,24 @@
     ChipModeId mode_id;
     return configureChipToSupportIfaceTypeInternal(wifi_chip, type, &mode_id);
 }
+
+bool doesChipSupportIfaceTypeInternal(const sp<IWifiChip>& wifi_chip,
+                                         IfaceType type) {
+    ChipModeId mode_id;
+    if (!wifi_chip.get()) {
+        return false;
+    }
+    const auto& status_and_modes = HIDL_INVOKE(wifi_chip, getAvailableModes);
+    if (status_and_modes.first.code != WifiStatusCode::SUCCESS) {
+        return false;
+    }
+    if (!findAnyModeSupportingIfaceType(type, status_and_modes.second,
+                                        &mode_id)) {
+        return false;
+    }
+
+    return true;
+}
 }  // namespace
 
 sp<IWifi> getWifi(const std::string& instance_name) {
@@ -205,6 +223,11 @@
                                                    configured_mode_id);
 }
 
+bool doesChipSupportIfaceType(const sp<IWifiChip>& wifi_chip,
+                                     IfaceType type) {
+    return doesChipSupportIfaceTypeInternal(wifi_chip, type);
+}
+
 void stopWifi(const std::string& instance_name) {
     sp<IWifi> wifi = IWifi::getService(instance_name);
     ASSERT_NE(wifi, nullptr);
diff --git a/wifi/1.0/vts/functional/wifi_hidl_test_utils.h b/wifi/1.0/vts/functional/wifi_hidl_test_utils.h
index 62c015c..876c316 100644
--- a/wifi/1.0/vts/functional/wifi_hidl_test_utils.h
+++ b/wifi/1.0/vts/functional/wifi_hidl_test_utils.h
@@ -49,6 +49,10 @@
     const android::sp<android::hardware::wifi::V1_0::IWifiChip>& wifi_chip,
     android::hardware::wifi::V1_0::IfaceType type,
     android::hardware::wifi::V1_0::ChipModeId* configured_mode_id);
+// Check whether wifi chip supports given interface type mode
+bool doesChipSupportIfaceType(
+        const android::sp<android::hardware::wifi::V1_0::IWifiChip>& wifi_chip,
+        android::hardware::wifi::V1_0::IfaceType type);
 // Used to trigger IWifi.stop() at the end of every test.
 void stopWifi(const std::string& instance_name);
 uint32_t getChipCapabilitiesLatest(
diff --git a/wifi/1.5/vts/functional/wifi_ap_iface_hidl_test.cpp b/wifi/1.5/vts/functional/wifi_ap_iface_hidl_test.cpp
index 424f934..c3bd4d7 100644
--- a/wifi/1.5/vts/functional/wifi_ap_iface_hidl_test.cpp
+++ b/wifi/1.5/vts/functional/wifi_ap_iface_hidl_test.cpp
@@ -58,12 +58,16 @@
             "wifi_softap_bridged_ap_supported");
         // Make sure to start with a clean state
         stopWifi(GetInstanceName());
+        // Read AP mode capabilities from the wifi chip modes
+        sp<IWifiChip> wifi_chip_ = getWifiChip_1_5(GetInstanceName());
+        isApModeSupport_ = doesChipSupportIfaceType(wifi_chip_, IfaceType::AP);
     }
 
     virtual void TearDown() override { stopWifi(GetInstanceName()); }
 
    protected:
     bool isBridgedSupport_ = false;
+    bool isApModeSupport_ = false;
     std::string GetInstanceName() { return GetParam(); }
 };
 
@@ -83,6 +87,7 @@
  * resetToFactoryMacAddress in non-bridged mode
  */
 TEST_P(WifiApIfaceHidlTest, resetToFactoryMacAddressTest) {
+    if (!isApModeSupport_) GTEST_SKIP() << "Missing AP support";
     sp<IWifiApIface> wifi_ap_iface = getWifiApIface_1_5(GetInstanceName());
     ASSERT_NE(nullptr, wifi_ap_iface.get());
     const auto& status = HIDL_INVOKE(wifi_ap_iface, resetToFactoryMacAddress);
@@ -93,6 +98,7 @@
  * getBridgedInstances in non-bridged mode
  */
 TEST_P(WifiApIfaceHidlTest, getBridgedInstancesTest) {
+    if (!isApModeSupport_) GTEST_SKIP() << "Missing AP support";
     sp<IWifiApIface> wifi_ap_iface = getWifiApIface_1_5(GetInstanceName());
     ASSERT_NE(nullptr, wifi_ap_iface.get());
     const auto& status_and_instances =
diff --git a/wifi/aidl/default/wifi_feature_flags.cpp b/wifi/aidl/default/wifi_feature_flags.cpp
index 3c9f042..35b4b4a 100644
--- a/wifi/aidl/default/wifi_feature_flags.cpp
+++ b/wifi/aidl/default/wifi_feature_flags.cpp
@@ -122,6 +122,7 @@
 #define AP IfaceConcurrencyType::AP
 #define AP_BRIDGED IfaceConcurrencyType::AP_BRIDGED
 #define P2P IfaceConcurrencyType::P2P
+#undef NAN  // undefine NAN from math.h
 #define NAN IfaceConcurrencyType::NAN_IFACE
 static const std::vector<IWifiChip::ChipMode> kChipModesPrimary{
         {kMainModeId, legacyToChipConcurrencyComboList({WIFI_HAL_INTERFACE_COMBINATIONS})},
diff --git a/wifi/aidl/vts/functional/wifi_aidl_test_utils.cpp b/wifi/aidl/vts/functional/wifi_aidl_test_utils.cpp
index ca3c4b7..986e3a8 100644
--- a/wifi/aidl/vts/functional/wifi_aidl_test_utils.cpp
+++ b/wifi/aidl/vts/functional/wifi_aidl_test_utils.cpp
@@ -197,9 +197,26 @@
 
 bool configureChipToSupportConcurrencyType(const std::shared_ptr<IWifiChip>& wifi_chip,
                                            IfaceConcurrencyType type, int* configured_mode_id) {
+    if (!wifi_chip.get()) {
+        return false;
+    }
     return configureChipToSupportConcurrencyTypeInternal(wifi_chip, type, configured_mode_id);
 }
 
+bool doesChipSupportConcurrencyType(const std::shared_ptr<IWifiChip>& wifi_chip,
+                                    IfaceConcurrencyType type) {
+    if (!wifi_chip.get()) {
+        return false;
+    }
+    std::vector<IWifiChip::ChipMode> chip_modes;
+    auto status = wifi_chip->getAvailableModes(&chip_modes);
+    if (!status.isOk()) {
+        return false;
+    }
+    int mode_id;
+    return findAnyModeSupportingConcurrencyType(type, chip_modes, &mode_id);
+}
+
 void stopWifiService(const char* instance_name) {
     std::shared_ptr<IWifi> wifi = getWifi(instance_name);
     if (wifi != nullptr) {
@@ -208,6 +225,9 @@
 }
 
 int32_t getChipFeatureSet(const std::shared_ptr<IWifiChip>& wifi_chip) {
+    if (!wifi_chip.get()) {
+        return 0;
+    }
     int32_t features = 0;
     if (wifi_chip->getFeatureSet(&features).isOk()) {
         return features;
diff --git a/wifi/aidl/vts/functional/wifi_aidl_test_utils.h b/wifi/aidl/vts/functional/wifi_aidl_test_utils.h
index 0d70c3b..921d689 100644
--- a/wifi/aidl/vts/functional/wifi_aidl_test_utils.h
+++ b/wifi/aidl/vts/functional/wifi_aidl_test_utils.h
@@ -42,6 +42,9 @@
 // Configure the chip in a mode to support the creation of the provided iface type.
 bool configureChipToSupportConcurrencyType(const std::shared_ptr<IWifiChip>& wifi_chip,
                                            IfaceConcurrencyType type, int* configured_mode_id);
+// Check whether the chip supports the creation of the provided iface type.
+bool doesChipSupportConcurrencyType(const std::shared_ptr<IWifiChip>& wifi_chip,
+                                    IfaceConcurrencyType type);
 // Used to trigger IWifi.stop() at the end of every test.
 void stopWifiService(const char* instance_name);
 int32_t getChipFeatureSet(const std::shared_ptr<IWifiChip>& wifi_chip);
diff --git a/wifi/aidl/vts/functional/wifi_chip_aidl_test.cpp b/wifi/aidl/vts/functional/wifi_chip_aidl_test.cpp
index bbd27f9..740f833 100644
--- a/wifi/aidl/vts/functional/wifi_chip_aidl_test.cpp
+++ b/wifi/aidl/vts/functional/wifi_chip_aidl_test.cpp
@@ -63,6 +63,10 @@
         return mode_id;
     }
 
+    bool isConcurrencyTypeSupported(IfaceConcurrencyType type) {
+        return doesChipSupportConcurrencyType(wifi_chip_, type);
+    }
+
     std::shared_ptr<IWifiStaIface> configureChipForStaAndGetIface() {
         std::shared_ptr<IWifiStaIface> iface;
         configureChipForConcurrencyType(IfaceConcurrencyType::STA);
@@ -532,6 +536,9 @@
  * CreateApIface
  */
 TEST_P(WifiChipAidlTest, CreateApIface) {
+    if (!isConcurrencyTypeSupported(IfaceConcurrencyType::AP)) {
+        GTEST_SKIP() << "AP is not supported";
+    }
     configureChipForApAndGetIface();
 }
 
@@ -549,6 +556,9 @@
  * CreateP2pIface
  */
 TEST_P(WifiChipAidlTest, CreateP2pIface) {
+    if (!isConcurrencyTypeSupported(IfaceConcurrencyType::P2P)) {
+        GTEST_SKIP() << "P2P is not supported";
+    }
     configureChipForP2pAndGetIface();
 }
 
@@ -583,6 +593,9 @@
  * GetP2pIfaceNames
  */
 TEST_P(WifiChipAidlTest, GetP2pIfaceNames) {
+    if (!isConcurrencyTypeSupported(IfaceConcurrencyType::P2P)) {
+        GTEST_SKIP() << "P2P is not supported";
+    }
     configureChipForConcurrencyType(IfaceConcurrencyType::P2P);
 
     std::vector<std::string> iface_names;
@@ -607,6 +620,9 @@
  * GetApIfaceNames
  */
 TEST_P(WifiChipAidlTest, GetApIfaceNames) {
+    if (!isConcurrencyTypeSupported(IfaceConcurrencyType::AP)) {
+        GTEST_SKIP() << "AP is not supported";
+    }
     configureChipForConcurrencyType(IfaceConcurrencyType::AP);
 
     std::vector<std::string> iface_names;
@@ -679,6 +695,9 @@
  * GetP2pIface
  */
 TEST_P(WifiChipAidlTest, GetP2pIface) {
+    if (!isConcurrencyTypeSupported(IfaceConcurrencyType::P2P)) {
+        GTEST_SKIP() << "P2P is not supported";
+    }
     std::shared_ptr<IWifiP2pIface> iface = configureChipForP2pAndGetIface();
     std::string iface_name = getP2pIfaceName(iface);
 
@@ -697,6 +716,9 @@
  * GetApIface
  */
 TEST_P(WifiChipAidlTest, GetApIface) {
+    if (!isConcurrencyTypeSupported(IfaceConcurrencyType::AP)) {
+        GTEST_SKIP() << "AP is not supported";
+    }
     std::shared_ptr<IWifiApIface> iface = configureChipForApAndGetIface();
     std::string iface_name = getApIfaceName(iface);
 
@@ -755,6 +777,9 @@
  * RemoveP2pIface
  */
 TEST_P(WifiChipAidlTest, RemoveP2pIface) {
+    if (!isConcurrencyTypeSupported(IfaceConcurrencyType::P2P)) {
+        GTEST_SKIP() << "P2P is not supported";
+    }
     std::shared_ptr<IWifiP2pIface> iface = configureChipForP2pAndGetIface();
     std::string iface_name = getP2pIfaceName(iface);
 
@@ -771,6 +796,9 @@
  * RemoveApIface
  */
 TEST_P(WifiChipAidlTest, RemoveApIface) {
+    if (!isConcurrencyTypeSupported(IfaceConcurrencyType::AP)) {
+        GTEST_SKIP() << "AP is not supported";
+    }
     std::shared_ptr<IWifiApIface> iface = configureChipForApAndGetIface();
     std::string iface_name = getApIfaceName(iface);
 
diff --git a/wifi/hostapd/1.0/vts/functional/hostapd_hidl_test.cpp b/wifi/hostapd/1.0/vts/functional/hostapd_hidl_test.cpp
index bb99ae4..46cba93 100644
--- a/wifi/hostapd/1.0/vts/functional/hostapd_hidl_test.cpp
+++ b/wifi/hostapd/1.0/vts/functional/hostapd_hidl_test.cpp
@@ -48,6 +48,13 @@
     virtual void SetUp() override {
         wifi_instance_name_ = std::get<0>(GetParam());
         hostapd_instance_name_ = std::get<1>(GetParam());
+
+        // Disable Wi-Fi framework to avoid interference
+        isWifiEnabled_ = isWifiFrameworkEnabled();
+        isScanAlwaysEnabled_ = isWifiScanAlwaysAvailable();
+        toggleWifiFramework(false);
+        toggleWifiScanAlwaysAvailable(false);
+
         stopSupplicantIfNeeded(wifi_instance_name_);
         startHostapdAndWaitForHidlService(wifi_instance_name_,
                                           hostapd_instance_name_);
@@ -58,14 +65,21 @@
     virtual void TearDown() override {
         HIDL_INVOKE_VOID_WITHOUT_ARGUMENTS(hostapd_, terminate);
         stopHostapd(wifi_instance_name_);
+
+        // Restore Wi-Fi framework state
+        toggleWifiFramework(isWifiEnabled_);
+        toggleWifiScanAlwaysAvailable(isScanAlwaysEnabled_);
     }
 
    protected:
-    std::string getPrimaryWlanIfaceName() {
+     bool isWifiEnabled_ = false;
+     bool isScanAlwaysEnabled_ = false;
+
+     std::string getPrimaryWlanIfaceName() {
         std::array<char, PROPERTY_VALUE_MAX> buffer;
         property_get("wifi.interface", buffer.data(), "wlan0");
         return buffer.data();
-    }
+     }
 
     IHostapd::IfaceParams getIfaceParamsWithAcs() {
         IHostapd::IfaceParams iface_params;
diff --git a/wifi/hostapd/1.0/vts/functional/hostapd_hidl_test_utils.cpp b/wifi/hostapd/1.0/vts/functional/hostapd_hidl_test_utils.cpp
index 56f285d..4c452fb 100644
--- a/wifi/hostapd/1.0/vts/functional/hostapd_hidl_test_utils.cpp
+++ b/wifi/hostapd/1.0/vts/functional/hostapd_hidl_test_utils.cpp
@@ -98,3 +98,24 @@
         ::android::hardware::wifi::hostapd::V1_1::IHostapd::castFrom(hostapd);
     return hostapd_1_1.get() != nullptr;
 }
+
+void toggleWifiFramework(bool enable) {
+    std::string cmd = "/system/bin/cmd wifi set-wifi-enabled ";
+    cmd += enable ? "enabled" : "disabled";
+    testing::checkSubstringInCommandOutput(cmd.c_str(), "X");
+}
+
+void toggleWifiScanAlwaysAvailable(bool enable) {
+    std::string cmd = "/system/bin/cmd wifi set-scan-always-available ";
+    cmd += enable ? "enabled" : "disabled";
+    testing::checkSubstringInCommandOutput(cmd.c_str(), "X");
+}
+
+bool isWifiFrameworkEnabled() {
+    return testing::checkSubstringInCommandOutput("/system/bin/cmd wifi status", "Wifi is enabled");
+}
+
+bool isWifiScanAlwaysAvailable() {
+    return testing::checkSubstringInCommandOutput("/system/bin/cmd wifi status",
+                                                  "Wifi scanning is always available");
+}
diff --git a/wifi/hostapd/1.0/vts/functional/hostapd_hidl_test_utils.h b/wifi/hostapd/1.0/vts/functional/hostapd_hidl_test_utils.h
index 893de1e..aa34c9a 100644
--- a/wifi/hostapd/1.0/vts/functional/hostapd_hidl_test_utils.h
+++ b/wifi/hostapd/1.0/vts/functional/hostapd_hidl_test_utils.h
@@ -17,14 +17,17 @@
 #ifndef HOSTAPD_HIDL_TEST_UTILS_H
 #define HOSTAPD_HIDL_TEST_UTILS_H
 
+#include <VtsCoreUtil.h>
 #include <android/hardware/wifi/hostapd/1.0/IHostapd.h>
 #include <android/hardware/wifi/hostapd/1.1/IHostapd.h>
 
 // Used to stop the android wifi framework before every test.
-void stopWifiFramework(const std::string& instance_name);
-void startWifiFramework(const std::string& instance_name);
 void stopSupplicantIfNeeded(const std::string& instance_name);
 void stopHostapd(const std::string& instance_name);
+void toggleWifiFramework(bool enable);
+void toggleWifiScanAlwaysAvailable(bool enable);
+bool isWifiFrameworkEnabled();
+bool isWifiScanAlwaysAvailable();
 // Used to configure the chip, driver and start wpa_hostapd before every
 // test.
 void startHostapdAndWaitForHidlService(
diff --git a/wifi/hostapd/aidl/vts/functional/hostapd_test_utils.h b/wifi/hostapd/aidl/vts/functional/hostapd_test_utils.h
index feee2c8..50a38d3 100644
--- a/wifi/hostapd/aidl/vts/functional/hostapd_test_utils.h
+++ b/wifi/hostapd/aidl/vts/functional/hostapd_test_utils.h
@@ -63,7 +63,7 @@
     LOG(ERROR) << "Unable to " << (enable ? "start" : "stop") << " supplicant";
 }
 
-void toggleWifiFramework(bool enable) {
+void toggleWifiFrameworkAndScan(bool enable) {
     if (enable) {
         std::system("svc wifi enable");
         std::system("cmd wifi set-scan-always-available enabled");
@@ -89,7 +89,7 @@
  *       any other clients to the HALs during testing.
  */
 void disableHalsAndFramework() {
-    toggleWifiFramework(false);
+    toggleWifiFrameworkAndScan(false);
     stopHostapd();
     stopVendorHal();
 
@@ -110,7 +110,7 @@
 }
 
 void startWifiFramework() {
-    toggleWifiFramework(true);
+    toggleWifiFrameworkAndScan(true);
 }
 
 std::string setupApIfaceAndGetName(bool isBridged) {