Snap for 8953554 from 552a9119e3cd4402c72e69c828ce525a096c87bd to mainline-tzdata4-release

Change-Id: If13a76246c14162ea39580dd637495b8e037fd14
diff --git a/audio/common/all-versions/default/7.0/HidlUtils.cpp b/audio/common/all-versions/default/7.0/HidlUtils.cpp
index 0fd2947..f89c898 100644
--- a/audio/common/all-versions/default/7.0/HidlUtils.cpp
+++ b/audio/common/all-versions/default/7.0/HidlUtils.cpp
@@ -898,7 +898,7 @@
     for (const auto& transport : transports) {
         switch (transport.audioCapability.getDiscriminator()) {
             case AudioTransport::AudioCapability::hidl_discriminator::profile:
-                if (halPort->num_audio_profiles > AUDIO_PORT_MAX_AUDIO_PROFILES) {
+                if (halPort->num_audio_profiles >= AUDIO_PORT_MAX_AUDIO_PROFILES) {
                     ALOGE("%s, too many audio profiles", __func__);
                     result = BAD_VALUE;
                     break;
@@ -914,7 +914,8 @@
                                 result);
                 break;
             case AudioTransport::AudioCapability::hidl_discriminator::edid:
-                if (halPort->num_extra_audio_descriptors > AUDIO_PORT_MAX_EXTRA_AUDIO_DESCRIPTORS) {
+                if (halPort->num_extra_audio_descriptors >=
+                    AUDIO_PORT_MAX_EXTRA_AUDIO_DESCRIPTORS) {
                     ALOGE("%s, too many extra audio descriptors", __func__);
                     result = BAD_VALUE;
                     break;
diff --git a/audio/common/all-versions/default/tests/hidlutils_tests.cpp b/audio/common/all-versions/default/tests/hidlutils_tests.cpp
index ec16b02..e6e2280 100644
--- a/audio/common/all-versions/default/tests/hidlutils_tests.cpp
+++ b/audio/common/all-versions/default/tests/hidlutils_tests.cpp
@@ -954,6 +954,18 @@
     EXPECT_TRUE(audio_port_configs_are_equal(&halConfig, &halConfigBack));
 }
 
+static AudioProfile generateValidAudioProfile() {
+    AudioProfile profile;
+    profile.format = toString(xsd::AudioFormat::AUDIO_FORMAT_PCM_16_BIT);
+    profile.sampleRates.resize(2);
+    profile.sampleRates[0] = 44100;
+    profile.sampleRates[1] = 48000;
+    profile.channelMasks.resize(2);
+    profile.channelMasks[0] = toString(xsd::AudioChannelMask::AUDIO_CHANNEL_OUT_MONO);
+    profile.channelMasks[1] = toString(xsd::AudioChannelMask::AUDIO_CHANNEL_OUT_STEREO);
+    return profile;
+}
+
 TEST(HidlUtils, ConvertInvalidAudioTransports) {
     hidl_vec<AudioTransport> invalid;
     struct audio_port_v7 halInvalid = {};
@@ -973,20 +985,32 @@
     invalid[0].audioCapability.edid(hidl_vec<uint8_t>(EXTRA_AUDIO_DESCRIPTOR_SIZE + 1));
     invalid[1].encapsulationType = "random string";
     EXPECT_EQ(BAD_VALUE, HidlUtils::audioTransportsToHal(invalid, &halInvalid));
+
+    // The size of audio profile must not be greater than the maximum value.
+    invalid.resize(0);
+    invalid.resize(AUDIO_PORT_MAX_AUDIO_PROFILES + 1);
+    for (size_t i = 0; i < invalid.size(); ++i) {
+        invalid[i].audioCapability.profile(generateValidAudioProfile());
+        invalid[i].encapsulationType =
+                toString(xsd::AudioEncapsulationType::AUDIO_ENCAPSULATION_TYPE_NONE);
+    }
+    EXPECT_EQ(BAD_VALUE, HidlUtils::audioTransportsToHal(invalid, &halInvalid));
+
+    // The size of extra audio descriptors must not be greater than the maximum value.
+    invalid.resize(0);
+    invalid.resize(AUDIO_PORT_MAX_EXTRA_AUDIO_DESCRIPTORS + 1);
+    for (size_t i = 0; i < invalid.size(); ++i) {
+        invalid[i].audioCapability.edid({0x11, 0x06, 0x01});
+        invalid[i].encapsulationType =
+                toString(xsd::AudioEncapsulationType::AUDIO_ENCAPSULATION_TYPE_IEC61937);
+    }
+    EXPECT_EQ(BAD_VALUE, HidlUtils::audioTransportsToHal(invalid, &halInvalid));
 }
 
 TEST(HidlUtils, ConvertAudioTransports) {
     hidl_vec<AudioTransport> transports;
     transports.resize(2);
-    AudioProfile profile;
-    profile.format = toString(xsd::AudioFormat::AUDIO_FORMAT_PCM_16_BIT);
-    profile.sampleRates.resize(2);
-    profile.sampleRates[0] = 44100;
-    profile.sampleRates[1] = 48000;
-    profile.channelMasks.resize(2);
-    profile.channelMasks[0] = toString(xsd::AudioChannelMask::AUDIO_CHANNEL_OUT_MONO);
-    profile.channelMasks[1] = toString(xsd::AudioChannelMask::AUDIO_CHANNEL_OUT_STEREO);
-    transports[0].audioCapability.profile(profile);
+    transports[0].audioCapability.profile(generateValidAudioProfile());
     hidl_vec<uint8_t> shortAudioDescriptor({0x11, 0x06, 0x01});
     transports[0].encapsulationType =
             toString(xsd::AudioEncapsulationType::AUDIO_ENCAPSULATION_TYPE_NONE);
diff --git a/audio/core/all-versions/vts/functional/7.0/AudioPrimaryHidlHalTest.cpp b/audio/core/all-versions/vts/functional/7.0/AudioPrimaryHidlHalTest.cpp
index dfc2386..505c54c 100644
--- a/audio/core/all-versions/vts/functional/7.0/AudioPrimaryHidlHalTest.cpp
+++ b/audio/core/all-versions/vts/functional/7.0/AudioPrimaryHidlHalTest.cpp
@@ -14,7 +14,11 @@
  * limitations under the License.
  */
 
+#include <fstream>
+#include <numeric>
+
 #include <android-base/chrono_utils.h>
+#include <cutils/properties.h>
 
 #include "Generators.h"
 
@@ -517,20 +521,10 @@
     }
 
     bool canQueryPresentationPosition() const {
-        auto maybeSinkAddress =
-                getCachedPolicyConfig().getSinkDeviceForMixPort(getDeviceName(), getMixPortName());
-        // Returning 'true' when no sink is found so the test can fail later with a more clear
-        // problem description.
-        return !maybeSinkAddress.has_value() ||
-               !xsd::isTelephonyDevice(maybeSinkAddress.value().deviceType);
+        return !xsd::isTelephonyDevice(address.deviceType);
     }
 
     void createPatchIfNeeded() {
-        auto maybeSinkAddress =
-                getCachedPolicyConfig().getSinkDeviceForMixPort(getDeviceName(), getMixPortName());
-        ASSERT_TRUE(maybeSinkAddress.has_value())
-                << "No sink device found for mix port " << getMixPortName() << " (module "
-                << getDeviceName() << ")";
         if (areAudioPatchesSupported()) {
             AudioPortConfig source;
             source.base.format.value(getConfig().base.format);
@@ -540,13 +534,13 @@
             source.ext.mix().ioHandle = helper.getIoHandle();
             source.ext.mix().useCase.stream({});
             AudioPortConfig sink;
-            sink.ext.device(maybeSinkAddress.value());
+            sink.ext.device(address);
             EXPECT_OK(getDevice()->createAudioPatch(hidl_vec<AudioPortConfig>{source},
                                                     hidl_vec<AudioPortConfig>{sink},
                                                     returnIn(res, mPatchHandle)));
             mHasPatch = res == Result::OK;
         } else {
-            EXPECT_OK(stream->setDevices({maybeSinkAddress.value()}));
+            EXPECT_OK(stream->setDevices({address}));
         }
     }
 
@@ -556,10 +550,6 @@
                 EXPECT_OK(getDevice()->releaseAudioPatch(mPatchHandle));
                 mHasPatch = false;
             }
-        } else {
-            if (stream) {
-                EXPECT_OK(stream->setDevices({address}));
-            }
         }
     }
 
@@ -575,16 +565,22 @@
         // Sometimes HAL doesn't have enough information until the audio data actually gets
         // consumed by the hardware.
         bool timedOut = false;
-        res = Result::INVALID_STATE;
-        for (android::base::Timer elapsed;
-             res != Result::OK && !writer.hasError() &&
-             !(timedOut = (elapsed.duration() >= kPositionChangeTimeout));) {
-            usleep(kWriteDurationUs);
-            ASSERT_OK(stream->getPresentationPosition(returnIn(res, framesInitial, ts)));
-            ASSERT_RESULT(okOrInvalidState, res);
+        if (!firstPosition || *firstPosition == std::numeric_limits<uint64_t>::max()) {
+            res = Result::INVALID_STATE;
+            for (android::base::Timer elapsed;
+                 res != Result::OK && !writer.hasError() &&
+                 !(timedOut = (elapsed.duration() >= kPositionChangeTimeout));) {
+                usleep(kWriteDurationUs);
+                ASSERT_OK(stream->getPresentationPosition(returnIn(res, framesInitial, ts)));
+                ASSERT_RESULT(okOrInvalidState, res);
+            }
+            ASSERT_FALSE(writer.hasError());
+            ASSERT_FALSE(timedOut);
+        } else {
+            // Use `firstPosition` instead of querying it from the HAL. This is used when
+            // `waitForPresentationPositionAdvance` is called in a loop.
+            framesInitial = *firstPosition;
         }
-        ASSERT_FALSE(writer.hasError());
-        ASSERT_FALSE(timedOut);
 
         uint64_t frames = framesInitial;
         for (android::base::Timer elapsed;
@@ -646,7 +642,7 @@
     ASSERT_OK(stream->standby());
     writer.resume();
 
-    uint64_t frames;
+    uint64_t frames = std::numeric_limits<uint64_t>::max();
     ASSERT_NO_FATAL_FAILURE(waitForPresentationPositionAdvance(writer, &frames));
     EXPECT_GT(frames, framesInitial);
 
@@ -691,24 +687,12 @@
         InputStreamTest::TearDown();
     }
 
-    bool canQueryCapturePosition() const {
-        auto maybeSourceAddress = getCachedPolicyConfig().getSourceDeviceForMixPort(
-                getDeviceName(), getMixPortName());
-        // Returning 'true' when no source is found so the test can fail later with a more clear
-        // problem description.
-        return !maybeSourceAddress.has_value() ||
-               !xsd::isTelephonyDevice(maybeSourceAddress.value().deviceType);
-    }
+    bool canQueryCapturePosition() const { return !xsd::isTelephonyDevice(address.deviceType); }
 
     void createPatchIfNeeded() {
-        auto maybeSourceAddress = getCachedPolicyConfig().getSourceDeviceForMixPort(
-                getDeviceName(), getMixPortName());
-        ASSERT_TRUE(maybeSourceAddress.has_value())
-                << "No source device found for mix port " << getMixPortName() << " (module "
-                << getDeviceName() << ")";
         if (areAudioPatchesSupported()) {
             AudioPortConfig source;
-            source.ext.device(maybeSourceAddress.value());
+            source.ext.device(address);
             AudioPortConfig sink;
             sink.base.format.value(getConfig().base.format);
             sink.base.sampleRateHz.value(getConfig().base.sampleRateHz);
@@ -721,7 +705,7 @@
                                                     returnIn(res, mPatchHandle)));
             mHasPatch = res == Result::OK;
         } else {
-            EXPECT_OK(stream->setDevices({maybeSourceAddress.value()}));
+            EXPECT_OK(stream->setDevices({address}));
         }
     }
 
@@ -731,10 +715,6 @@
                 EXPECT_OK(getDevice()->releaseAudioPatch(mPatchHandle));
                 mHasPatch = false;
             }
-        } else {
-            if (stream) {
-                EXPECT_OK(stream->setDevices({address}));
-            }
         }
     }
 
@@ -864,14 +844,8 @@
     }
     ASSERT_OK(res);
 
-    auto maybeSourceAddress =
-            getCachedPolicyConfig().getSourceDeviceForMixPort(getDeviceName(), getMixPortName());
-    ASSERT_TRUE(maybeSourceAddress.has_value())
-            << "No source device found for mix port " << getMixPortName() << " (module "
-            << getDeviceName() << ")";
-
     for (auto microphone : microphones) {
-        if (microphone.deviceAddress == maybeSourceAddress.value()) {
+        if (microphone.deviceAddress == address) {
             StreamReader reader(stream.get(), stream->getBufferSize());
             ASSERT_TRUE(reader.start());
             reader.pause();  // This ensures that at least one read has happened.
@@ -889,3 +863,176 @@
                         ::testing::ValuesIn(getBuiltinMicConfigParameters()),
                         &DeviceConfigParameterToString);
 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(MicrophoneInfoInputStreamTest);
+
+static const std::vector<DeviceConfigParameter>& getOutputDeviceCompressedConfigParameters(
+        const AudioConfigBase& configToMatch) {
+    static const std::vector<DeviceConfigParameter> parameters = [&] {
+        auto allParams = getOutputDeviceConfigParameters();
+        std::vector<DeviceConfigParameter> compressedParams;
+        std::copy_if(allParams.begin(), allParams.end(), std::back_inserter(compressedParams),
+                     [&](auto cfg) {
+                         if (std::get<PARAM_CONFIG>(cfg).base != configToMatch) return false;
+                         const auto& flags = std::get<PARAM_FLAGS>(cfg);
+                         return std::find_if(flags.begin(), flags.end(), [](const auto& flag) {
+                                    return flag ==
+                                           toString(xsd::AudioInOutFlag::
+                                                            AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
+                                }) != flags.end();
+                     });
+        return compressedParams;
+    }();
+    return parameters;
+}
+
+class CompressedOffloadOutputStreamTest : public PcmOnlyConfigOutputStreamTest {
+  public:
+    void loadData(const std::string& fileName, std::vector<uint8_t>* data) {
+        std::ifstream is(fileName, std::ios::in | std::ios::binary);
+        ASSERT_TRUE(is.good()) << "Failed to open file " << fileName;
+        is.seekg(0, is.end);
+        data->reserve(data->size() + is.tellg());
+        is.seekg(0, is.beg);
+        data->insert(data->end(), std::istreambuf_iterator<char>(is),
+                     std::istreambuf_iterator<char>());
+        ASSERT_TRUE(!is.fail()) << "Failed to read from file " << fileName;
+    }
+};
+
+class OffloadCallbacks : public IStreamOutCallback {
+  public:
+    Return<void> onDrainReady() override {
+        ALOGI("onDrainReady");
+        {
+            std::lock_guard lg(mLock);
+            mOnDrainReady = true;
+        }
+        mCondVar.notify_one();
+        return {};
+    }
+    Return<void> onWriteReady() override { return {}; }
+    Return<void> onError() override {
+        ALOGW("onError");
+        {
+            std::lock_guard lg(mLock);
+            mOnError = true;
+        }
+        mCondVar.notify_one();
+        return {};
+    }
+    bool waitForDrainReadyOrError() {
+        std::unique_lock l(mLock);
+        if (!mOnDrainReady && !mOnError) {
+            mCondVar.wait(l, [&]() { return mOnDrainReady || mOnError; });
+        }
+        const bool success = !mOnError;
+        mOnDrainReady = mOnError = false;
+        return success;
+    }
+
+  private:
+    std::mutex mLock;
+    bool mOnDrainReady = false;
+    bool mOnError = false;
+    std::condition_variable mCondVar;
+};
+
+TEST_P(CompressedOffloadOutputStreamTest, Mp3FormatGaplessOffload) {
+    doc::test("Check that compressed offload mix ports for MP3 implement gapless offload");
+    const auto& flags = getOutputFlags();
+    const bool isNewDeviceLaunchingOnTPlus = property_get_int32("ro.vendor.api_level", 0) >= 33;
+    // See test instantiation, only offload MP3 mix ports are used.
+    if (std::find_if(flags.begin(), flags.end(), [](const auto& flag) {
+            return flag == toString(xsd::AudioInOutFlag::AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD);
+        }) == flags.end()) {
+        if (isNewDeviceLaunchingOnTPlus) {
+            FAIL() << "New devices launching on Android T+ must support gapless offload, "
+                   << "see VSR-4.3-001";
+        } else {
+            GTEST_SKIP() << "Compressed offload mix port does not support gapless offload";
+        }
+    }
+    std::vector<uint8_t> offloadData;
+    ASSERT_NO_FATAL_FAILURE(loadData("/data/local/tmp/sine882hz3s.mp3", &offloadData));
+    ASSERT_FALSE(offloadData.empty());
+    ASSERT_NO_FATAL_FAILURE(createPatchIfNeeded());
+    const int presentationeEndPrecisionMs = 1000;
+    const int sampleRate = 44100;
+    const int significantSampleNumber = (presentationeEndPrecisionMs * sampleRate) / 1000;
+    const int delay = 576 + 1000;
+    const int padding = 756 + 1000;
+    const int durationMs = 3000 - 44;
+    auto start = std::chrono::steady_clock::now();
+    auto callbacks = sp<OffloadCallbacks>::make();
+    std::mutex presentationEndLock;
+    std::vector<float> presentationEndTimes;
+    // StreamWriter plays 'offloadData' in a loop, possibly using multiple calls to 'write', this
+    // depends on the relative sizes of 'offloadData' and the HAL buffer. Writer calls 'onDataStart'
+    // each time it starts writing the buffer from the beginning, and 'onDataWrap' callback each
+    // time it wraps around the buffer.
+    StreamWriter writer(
+            stream.get(), stream->getBufferSize(), std::move(offloadData),
+            [&]() /* onDataStart */ { start = std::chrono::steady_clock::now(); },
+            [&]() /* onDataWrap */ {
+                Return<Result> ret(Result::OK);
+                // Decrease the volume since the test plays a loud sine wave.
+                ret = stream->setVolume(0.1, 0.1);
+                if (!ret.isOk() || ret != Result::OK) {
+                    ALOGE("%s: setVolume failed: %s", __func__, toString(ret).c_str());
+                    return false;
+                }
+                ret = Parameters::set(
+                        stream, {{AUDIO_OFFLOAD_CODEC_DELAY_SAMPLES, std::to_string(delay)},
+                                 {AUDIO_OFFLOAD_CODEC_PADDING_SAMPLES, std::to_string(padding)}});
+                if (!ret.isOk() || ret != Result::OK) {
+                    ALOGE("%s: setParameters failed: %s", __func__, toString(ret).c_str());
+                    return false;
+                }
+                ret = stream->drain(AudioDrain::EARLY_NOTIFY);
+                if (!ret.isOk() || ret != Result::OK) {
+                    ALOGE("%s: drain failed: %s", __func__, toString(ret).c_str());
+                    return false;
+                }
+                // FIXME: On some SoCs intermittent errors are possible, ignore them.
+                if (callbacks->waitForDrainReadyOrError()) {
+                    const float duration = std::chrono::duration_cast<std::chrono::milliseconds>(
+                                                   std::chrono::steady_clock::now() - start)
+                                                   .count();
+                    std::lock_guard lg(presentationEndLock);
+                    presentationEndTimes.push_back(duration);
+                }
+                return true;
+            });
+    ASSERT_OK(stream->setCallback(callbacks));
+    ASSERT_TRUE(writer.start());
+    // How many times to loop the track so that the sum of gapless delay and padding from
+    // the first presentation end to the last is at least 'presentationeEndPrecisionMs'.
+    const int playbackNumber = (int)(significantSampleNumber / ((float)delay + padding) + 1);
+    for (bool done = false; !done;) {
+        usleep(presentationeEndPrecisionMs * 1000);
+        {
+            std::lock_guard lg(presentationEndLock);
+            done = presentationEndTimes.size() >= playbackNumber;
+        }
+        ASSERT_FALSE(writer.hasError()) << "Recent write or drain operation has failed";
+    }
+    const float avgDuration =
+            std::accumulate(presentationEndTimes.begin(), presentationEndTimes.end(), 0.0) /
+            presentationEndTimes.size();
+    std::stringstream observedEndTimes;
+    std::copy(presentationEndTimes.begin(), presentationEndTimes.end(),
+              std::ostream_iterator<float>(observedEndTimes, ", "));
+    EXPECT_NEAR(durationMs, avgDuration, presentationeEndPrecisionMs * 0.1)
+            << "Observed durations: " << observedEndTimes.str();
+    writer.stop();
+    EXPECT_OK(stream->clearCallback());
+    releasePatchIfNeeded();
+}
+
+INSTANTIATE_TEST_CASE_P(
+        CompressedOffloadOutputStream, CompressedOffloadOutputStreamTest,
+        ::testing::ValuesIn(getOutputDeviceCompressedConfigParameters(AudioConfigBase{
+                .format = xsd::toString(xsd::AudioFormat::AUDIO_FORMAT_MP3),
+                .sampleRateHz = 44100,
+                .channelMask = xsd::toString(xsd::AudioChannelMask::AUDIO_CHANNEL_OUT_STEREO)})),
+        &DeviceConfigParameterToString);
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(CompressedOffloadOutputStreamTest);
diff --git a/audio/core/all-versions/vts/functional/7.0/Generators.cpp b/audio/core/all-versions/vts/functional/7.0/Generators.cpp
index f936d0a..8b955b6 100644
--- a/audio/core/all-versions/vts/functional/7.0/Generators.cpp
+++ b/audio/core/all-versions/vts/functional/7.0/Generators.cpp
@@ -57,9 +57,6 @@
 
 static std::tuple<std::vector<AudioInOutFlag>, bool> generateOutFlags(
         const xsd::MixPorts::MixPort& mixPort) {
-    static const std::vector<AudioInOutFlag> offloadFlags = {
-            toString(xsd::AudioInOutFlag::AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
-            toString(xsd::AudioInOutFlag::AUDIO_OUTPUT_FLAG_DIRECT)};
     std::vector<AudioInOutFlag> flags;
     bool isOffload = false;
     if (mixPort.hasFlags()) {
@@ -67,14 +64,10 @@
         isOffload = std::find(xsdFlags.begin(), xsdFlags.end(),
                               xsd::AudioInOutFlag::AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) !=
                     xsdFlags.end();
-        if (!isOffload) {
-            for (auto flag : xsdFlags) {
-                if (flag != xsd::AudioInOutFlag::AUDIO_OUTPUT_FLAG_PRIMARY) {
-                    flags.push_back(toString(flag));
-                }
+        for (auto flag : xsdFlags) {
+            if (flag != xsd::AudioInOutFlag::AUDIO_OUTPUT_FLAG_PRIMARY) {
+                flags.push_back(toString(flag));
             }
-        } else {
-            flags = offloadFlags;
         }
     }
     return {flags, isOffload};
@@ -85,10 +78,10 @@
             .base = base,
             .streamType = toString(xsd::AudioStreamType::AUDIO_STREAM_MUSIC),
             .usage = toString(xsd::AudioUsage::AUDIO_USAGE_MEDIA),
-            .bitRatePerSecond = 320,
+            .bitRatePerSecond = 192,  // as in sine882hz3s.mp3
             .durationMicroseconds = -1,
             .bitWidth = 16,
-            .bufferSize = 256  // arbitrary value
+            .bufferSize = 72000  // 3 seconds at 192 kbps, as in sine882hz3s.mp3
     };
 }
 
@@ -100,11 +93,10 @@
         if (!module || !module->getFirstMixPorts()) break;
         for (const auto& mixPort : module->getFirstMixPorts()->getMixPort()) {
             if (mixPort.getRole() != xsd::Role::source) continue;  // not an output profile
-            if (getCachedPolicyConfig()
-                        .getAttachedSinkDeviceForMixPort(moduleName, mixPort.getName())
-                        .empty()) {
-                continue;  // no attached device
-            }
+            const auto attachedDeviceAddress =
+                    getCachedPolicyConfig().getDeviceAddressOfSinkDeviceAttachedToMixPort(
+                            moduleName, mixPort.getName());
+            if (!attachedDeviceAddress.has_value()) continue;
             auto [flags, isOffload] = generateOutFlags(mixPort);
             for (const auto& profile : mixPort.getProfile()) {
                 if (!profile.hasFormat() || !profile.hasSamplingRates() ||
@@ -118,7 +110,8 @@
                     if (isOffload) {
                         config.offloadInfo.info(generateOffloadInfo(config.base));
                     }
-                    result.emplace_back(device, mixPort.getName(), config, flags);
+                    result.emplace_back(device, mixPort.getName(), attachedDeviceAddress.value(),
+                                        config, flags);
                     if (oneProfilePerDevice) break;
                 }
                 if (oneProfilePerDevice) break;
@@ -162,13 +155,16 @@
                             profile.getFormat(),
                             static_cast<uint32_t>(profile.getSamplingRates()[0]),
                             toString(profile.getChannelMasks()[0])};
+                    DeviceAddress defaultDevice = {
+                            toString(xsd::AudioDevice::AUDIO_DEVICE_OUT_DEFAULT), {}};
                     {
                         AudioConfig config{.base = validBase};
                         config.base.channelMask = "random_string";
                         if (isOffload) {
                             config.offloadInfo.info(generateOffloadInfo(validBase));
                         }
-                        result.emplace_back(device, mixPort.getName(), config, validFlags);
+                        result.emplace_back(device, mixPort.getName(), defaultDevice, config,
+                                            validFlags);
                     }
                     {
                         AudioConfig config{.base = validBase};
@@ -176,7 +172,8 @@
                         if (isOffload) {
                             config.offloadInfo.info(generateOffloadInfo(validBase));
                         }
-                        result.emplace_back(device, mixPort.getName(), config, validFlags);
+                        result.emplace_back(device, mixPort.getName(), defaultDevice, config,
+                                            validFlags);
                     }
                     if (generateInvalidFlags) {
                         AudioConfig config{.base = validBase};
@@ -184,32 +181,37 @@
                             config.offloadInfo.info(generateOffloadInfo(validBase));
                         }
                         std::vector<AudioInOutFlag> flags = {"random_string", ""};
-                        result.emplace_back(device, mixPort.getName(), config, flags);
+                        result.emplace_back(device, mixPort.getName(), defaultDevice, config,
+                                            flags);
                     }
                     if (isOffload) {
                         {
                             AudioConfig config{.base = validBase};
                             config.offloadInfo.info(generateOffloadInfo(validBase));
                             config.offloadInfo.info().base.channelMask = "random_string";
-                            result.emplace_back(device, mixPort.getName(), config, validFlags);
+                            result.emplace_back(device, mixPort.getName(), defaultDevice, config,
+                                                validFlags);
                         }
                         {
                             AudioConfig config{.base = validBase};
                             config.offloadInfo.info(generateOffloadInfo(validBase));
                             config.offloadInfo.info().base.format = "random_string";
-                            result.emplace_back(device, mixPort.getName(), config, validFlags);
+                            result.emplace_back(device, mixPort.getName(), defaultDevice, config,
+                                                validFlags);
                         }
                         {
                             AudioConfig config{.base = validBase};
                             config.offloadInfo.info(generateOffloadInfo(validBase));
                             config.offloadInfo.info().streamType = "random_string";
-                            result.emplace_back(device, mixPort.getName(), config, validFlags);
+                            result.emplace_back(device, mixPort.getName(), defaultDevice, config,
+                                                validFlags);
                         }
                         {
                             AudioConfig config{.base = validBase};
                             config.offloadInfo.info(generateOffloadInfo(validBase));
                             config.offloadInfo.info().usage = "random_string";
-                            result.emplace_back(device, mixPort.getName(), config, validFlags);
+                            result.emplace_back(device, mixPort.getName(), defaultDevice, config,
+                                                validFlags);
                         }
                         hasOffloadConfig = true;
                     } else {
@@ -233,11 +235,10 @@
         if (!module || !module->getFirstMixPorts()) break;
         for (const auto& mixPort : module->getFirstMixPorts()->getMixPort()) {
             if (mixPort.getRole() != xsd::Role::sink) continue;  // not an input profile
-            if (getCachedPolicyConfig()
-                        .getAttachedSourceDeviceForMixPort(moduleName, mixPort.getName())
-                        .empty()) {
-                continue;  // no attached device
-            }
+            const auto attachedDeviceAddress =
+                    getCachedPolicyConfig().getDeviceAddressOfSourceDeviceAttachedToMixPort(
+                            moduleName, mixPort.getName());
+            if (!attachedDeviceAddress.has_value()) continue;
             std::vector<AudioInOutFlag> flags;
             if (mixPort.hasFlags()) {
                 std::transform(mixPort.getFlags().begin(), mixPort.getFlags().end(),
@@ -250,7 +251,8 @@
                 auto configs = combineAudioConfig(profile.getChannelMasks(),
                                                   profile.getSamplingRates(), profile.getFormat());
                 for (const auto& config : configs) {
-                    result.emplace_back(device, mixPort.getName(), config, flags);
+                    result.emplace_back(device, mixPort.getName(), attachedDeviceAddress.value(),
+                                        config, flags);
                     if (oneProfilePerDevice) break;
                 }
                 if (oneProfilePerDevice) break;
@@ -298,20 +300,25 @@
                             profile.getFormat(),
                             static_cast<uint32_t>(profile.getSamplingRates()[0]),
                             toString(profile.getChannelMasks()[0])};
+                    DeviceAddress defaultDevice = {
+                            toString(xsd::AudioDevice::AUDIO_DEVICE_IN_DEFAULT), {}};
                     {
                         AudioConfig config{.base = validBase};
                         config.base.channelMask = "random_string";
-                        result.emplace_back(device, mixPort.getName(), config, validFlags);
+                        result.emplace_back(device, mixPort.getName(), defaultDevice, config,
+                                            validFlags);
                     }
                     {
                         AudioConfig config{.base = validBase};
                         config.base.format = "random_string";
-                        result.emplace_back(device, mixPort.getName(), config, validFlags);
+                        result.emplace_back(device, mixPort.getName(), defaultDevice, config,
+                                            validFlags);
                     }
                     if (generateInvalidFlags) {
                         AudioConfig config{.base = validBase};
                         std::vector<AudioInOutFlag> flags = {"random_string", ""};
-                        result.emplace_back(device, mixPort.getName(), config, flags);
+                        result.emplace_back(device, mixPort.getName(), defaultDevice, config,
+                                            flags);
                     }
                     hasConfig = true;
                     break;
diff --git a/audio/core/all-versions/vts/functional/7.0/PolicyConfig.h b/audio/core/all-versions/vts/functional/7.0/PolicyConfig.h
index 4aea503..c1d5669 100644
--- a/audio/core/all-versions/vts/functional/7.0/PolicyConfig.h
+++ b/audio/core/all-versions/vts/functional/7.0/PolicyConfig.h
@@ -61,6 +61,18 @@
     const std::set<std::string>& getModulesWithDevicesNames() const {
         return mModulesWithDevicesNames;
     }
+    std::optional<DeviceAddress> getDeviceAddressOfSinkDeviceAttachedToMixPort(
+            const std::string& moduleName, const std::string& mixPortName) const {
+        const auto attachedDevicePort = getAttachedSinkDeviceForMixPort(moduleName, mixPortName);
+        if (attachedDevicePort.empty()) return {};
+        return getDeviceAddressOfDevicePort(moduleName, attachedDevicePort);
+    }
+    std::optional<DeviceAddress> getDeviceAddressOfSourceDeviceAttachedToMixPort(
+            const std::string& moduleName, const std::string& mixPortName) const {
+        const auto attachedDevicePort = getAttachedSourceDeviceForMixPort(moduleName, mixPortName);
+        if (attachedDevicePort.empty()) return {};
+        return getDeviceAddressOfDevicePort(moduleName, attachedDevicePort);
+    }
     std::string getAttachedSinkDeviceForMixPort(const std::string& moduleName,
                                                 const std::string& mixPortName) const {
         return findAttachedDevice(getAttachedDevices(moduleName),
@@ -84,8 +96,6 @@
     const std::vector<std::string>& getAttachedDevices(const std::string& moduleName) const;
     std::optional<DeviceAddress> getDeviceAddressOfDevicePort(
             const std::string& moduleName, const std::string& devicePortName) const;
-    std::string getDevicePortTagNameFromType(const std::string& moduleName,
-                                             const AudioDevice& deviceType) const;
     std::set<std::string> getSinkDevicesForMixPort(const std::string& moduleName,
                                                    const std::string& mixPortName) const;
     std::set<std::string> getSourceDevicesForMixPort(const std::string& moduleName,
diff --git a/audio/core/all-versions/vts/functional/Android.bp b/audio/core/all-versions/vts/functional/Android.bp
index c757032..daed7a8 100644
--- a/audio/core/all-versions/vts/functional/Android.bp
+++ b/audio/core/all-versions/vts/functional/Android.bp
@@ -34,6 +34,7 @@
     ],
     shared_libs: [
         "libbinder",
+        "libcutils",
         "libfmq",
         "libxml2",
     ],
@@ -190,6 +191,7 @@
     ],
     data: [
         ":audio_policy_configuration_V7_0",
+        "data/sine882hz3s.mp3",
     ],
     // Use test_config for vts suite.
     // TODO(b/146104851): Add auto-gen rules and remove it.
@@ -223,6 +225,7 @@
     ],
     data: [
         ":audio_policy_configuration_V7_1",
+        "data/sine882hz3s.mp3",
     ],
     // Use test_config for vts suite.
     // TODO(b/146104851): Add auto-gen rules and remove it.
diff --git a/audio/core/all-versions/vts/functional/AudioPrimaryHidlHalTest.h b/audio/core/all-versions/vts/functional/AudioPrimaryHidlHalTest.h
index 38e9e5f..e46e5b4 100644
--- a/audio/core/all-versions/vts/functional/AudioPrimaryHidlHalTest.h
+++ b/audio/core/all-versions/vts/functional/AudioPrimaryHidlHalTest.h
@@ -617,7 +617,8 @@
                     std::get<PARAM_FLAGS>(info.param)));
 #elif MAJOR_VERSION >= 7
     const auto configPart =
-            std::to_string(config.base.sampleRateHz) + "_" +
+            ::testing::PrintToString(std::get<PARAM_ATTACHED_DEV_ADDR>(info.param).deviceType) +
+            "_" + std::to_string(config.base.sampleRateHz) + "_" +
             // The channel masks and flags are vectors of strings, just need to sanitize them.
             SanitizeStringForGTestName(::testing::PrintToString(config.base.channelMask)) + "_" +
             SanitizeStringForGTestName(::testing::PrintToString(std::get<PARAM_FLAGS>(info.param)));
@@ -658,6 +659,9 @@
                 std::get<INDEX_OUTPUT>(std::get<PARAM_FLAGS>(GetParam())));
     }
 #elif MAJOR_VERSION >= 7
+    DeviceAddress getAttachedDeviceAddress() const {
+        return std::get<PARAM_ATTACHED_DEV_ADDR>(GetParam());
+    }
     hidl_vec<AudioInOutFlag> getInputFlags() const { return std::get<PARAM_FLAGS>(GetParam()); }
     hidl_vec<AudioInOutFlag> getOutputFlags() const { return std::get<PARAM_FLAGS>(GetParam()); }
 #endif
@@ -933,6 +937,15 @@
 
     StreamWriter(IStreamOut* stream, size_t bufferSize)
         : mStream(stream), mBufferSize(bufferSize), mData(mBufferSize) {}
+    StreamWriter(IStreamOut* stream, size_t bufferSize, std::vector<uint8_t>&& data,
+                 std::function<void()> onDataStart, std::function<bool()> onDataWrap)
+        : mStream(stream),
+          mBufferSize(bufferSize),
+          mData(std::move(data)),
+          mOnDataStart(onDataStart),
+          mOnDataWrap(onDataWrap) {
+        ALOGI("StreamWriter data size: %d", (int)mData.size());
+    }
     ~StreamWriter() {
         stop();
         if (mEfGroup) {
@@ -998,9 +1011,12 @@
             ALOGE("command message queue write failed");
             return false;
         }
-        const size_t dataSize = std::min(mData.size(), mDataMQ->availableToWrite());
-        bool success = mDataMQ->write(mData.data(), dataSize);
+        if (mDataPosition == 0) mOnDataStart();
+        const size_t dataSize = std::min(mData.size() - mDataPosition, mDataMQ->availableToWrite());
+        bool success = mDataMQ->write(mData.data() + mDataPosition, dataSize);
         ALOGE_IF(!success, "data message queue write failed");
+        mDataPosition += dataSize;
+        if (mDataPosition >= mData.size()) mDataPosition = 0;
         mEfGroup->wake(static_cast<uint32_t>(MessageQueueFlagBits::NOT_EMPTY));
 
         uint32_t efState = 0;
@@ -1026,6 +1042,9 @@
             ALOGE("bad wait status: %d", ret);
             success = false;
         }
+        if (success && mDataPosition == 0) {
+            success = mOnDataWrap();
+        }
         return success;
     }
 
@@ -1033,6 +1052,9 @@
     IStreamOut* const mStream;
     const size_t mBufferSize;
     std::vector<uint8_t> mData;
+    std::function<void()> mOnDataStart = []() {};
+    std::function<bool()> mOnDataWrap = []() { return true; };
+    size_t mDataPosition = 0;
     std::unique_ptr<CommandMQ> mCommandMQ;
     std::unique_ptr<DataMQ> mDataMQ;
     std::unique_ptr<StatusMQ> mStatusMQ;
@@ -1047,7 +1069,7 @@
 #if MAJOR_VERSION <= 6
         address.device = AudioDevice::OUT_DEFAULT;
 #elif MAJOR_VERSION >= 7
-        address.deviceType = toString(xsd::AudioDevice::AUDIO_DEVICE_OUT_DEFAULT);
+        address = getAttachedDeviceAddress();
 #endif
         const AudioConfig& config = getConfig();
         auto flags = getOutputFlags();
@@ -1243,16 +1265,11 @@
 #if MAJOR_VERSION <= 6
         address.device = AudioDevice::IN_DEFAULT;
 #elif MAJOR_VERSION >= 7
-        auto maybeSourceAddress = getCachedPolicyConfig().getSourceDeviceForMixPort(
-                getDeviceName(), getMixPortName());
+        address = getAttachedDeviceAddress();
         auto& metadata = initMetadata.tracks[0];
-        if (maybeSourceAddress.has_value() &&
-            !xsd::isTelephonyDevice(maybeSourceAddress.value().deviceType)) {
-            address = maybeSourceAddress.value();
+        if (!xsd::isTelephonyDevice(address.deviceType)) {
             metadata.source = toString(xsd::AudioSource::AUDIO_SOURCE_UNPROCESSED);
             metadata.channelMask = getConfig().base.channelMask;
-        } else {
-            address.deviceType = toString(xsd::AudioDevice::AUDIO_DEVICE_IN_DEFAULT);
         }
 #if MAJOR_VERSION == 7 && MINOR_VERSION >= 1
         auto flagsIt = std::find(flags.begin(), flags.end(),
diff --git a/audio/core/all-versions/vts/functional/AudioTestDefinitions.h b/audio/core/all-versions/vts/functional/AudioTestDefinitions.h
index 802b87b..3de06c3 100644
--- a/audio/core/all-versions/vts/functional/AudioTestDefinitions.h
+++ b/audio/core/all-versions/vts/functional/AudioTestDefinitions.h
@@ -39,9 +39,10 @@
         std::variant<android::hardware::audio::common::COMMON_TYPES_CPP_VERSION::AudioInputFlag,
                      android::hardware::audio::common::COMMON_TYPES_CPP_VERSION::AudioOutputFlag>>;
 #elif MAJOR_VERSION >= 7
-enum { PARAM_DEVICE, PARAM_PORT_NAME, PARAM_CONFIG, PARAM_FLAGS };
+enum { PARAM_DEVICE, PARAM_PORT_NAME, PARAM_ATTACHED_DEV_ADDR, PARAM_CONFIG, PARAM_FLAGS };
 using DeviceConfigParameter =
         std::tuple<DeviceParameter, std::string,
+                   android::hardware::audio::common::COMMON_TYPES_CPP_VERSION::DeviceAddress,
                    android::hardware::audio::common::COMMON_TYPES_CPP_VERSION::AudioConfig,
                    std::vector<android::hardware::audio::CORE_TYPES_CPP_VERSION::AudioInOutFlag>>;
 #endif
diff --git a/audio/core/all-versions/vts/functional/VtsHalAudioV7_0TargetTest.xml b/audio/core/all-versions/vts/functional/VtsHalAudioV7_0TargetTest.xml
index f0e2695..8da5744 100644
--- a/audio/core/all-versions/vts/functional/VtsHalAudioV7_0TargetTest.xml
+++ b/audio/core/all-versions/vts/functional/VtsHalAudioV7_0TargetTest.xml
@@ -29,6 +29,7 @@
         <option name="cleanup" value="true" />
         <option name="push" value="VtsHalAudioV7_0TargetTest->/data/local/tmp/VtsHalAudioV7_0TargetTest" />
         <option name="push" value="audio_policy_configuration_V7_0.xsd->/data/local/tmp/audio_policy_configuration_V7_0.xsd" />
+        <option name="push" value="sine882hz3s.mp3->/data/local/tmp/sine882hz3s.mp3" />
     </target_preparer>
 
     <test class="com.android.tradefed.testtype.GTest" >
diff --git a/audio/core/all-versions/vts/functional/VtsHalAudioV7_1TargetTest.xml b/audio/core/all-versions/vts/functional/VtsHalAudioV7_1TargetTest.xml
index 7ce1477..227df18 100644
--- a/audio/core/all-versions/vts/functional/VtsHalAudioV7_1TargetTest.xml
+++ b/audio/core/all-versions/vts/functional/VtsHalAudioV7_1TargetTest.xml
@@ -29,6 +29,8 @@
         <option name="cleanup" value="true" />
         <option name="push" value="VtsHalAudioV7_1TargetTest->/data/local/tmp/VtsHalAudioV7_1TargetTest" />
         <option name="push" value="audio_policy_configuration_V7_1.xsd->/data/local/tmp/audio_policy_configuration_V7_1.xsd" />
+        <option name="push" value="sine882hz3s.mp3->/data/local/tmp/sine882hz3s.mp3" />
+
     </target_preparer>
 
     <test class="com.android.tradefed.testtype.GTest" >
diff --git a/audio/core/all-versions/vts/functional/data/sine882hz3s.mp3 b/audio/core/all-versions/vts/functional/data/sine882hz3s.mp3
new file mode 100644
index 0000000..0604f9b
--- /dev/null
+++ b/audio/core/all-versions/vts/functional/data/sine882hz3s.mp3
Binary files differ
diff --git a/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/1/.hash b/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/1/.hash
index 7bb15e8..f478504 100644
--- a/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/1/.hash
+++ b/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/1/.hash
@@ -1 +1 @@
-38469e5a0359c95015bea304c463b686cf4ee9ca
+8610b651e162c614a97542d6f4ed039c969823e5
diff --git a/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/1/android/hardware/automotive/vehicle/VehicleApPowerStateConfigFlag.aidl b/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/1/android/hardware/automotive/vehicle/VehicleApPowerStateConfigFlag.aidl
index 7e48eba..d7b874a 100644
--- a/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/1/android/hardware/automotive/vehicle/VehicleApPowerStateConfigFlag.aidl
+++ b/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/1/android/hardware/automotive/vehicle/VehicleApPowerStateConfigFlag.aidl
@@ -36,5 +36,5 @@
 enum VehicleApPowerStateConfigFlag {
   ENABLE_DEEP_SLEEP_FLAG = 1,
   CONFIG_SUPPORT_TIMER_POWER_ON_FLAG = 2,
-  ENABLE_HIBERNATION_FLAG = 3,
+  ENABLE_HIBERNATION_FLAG = 4,
 }
diff --git a/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/current/android/hardware/automotive/vehicle/VehicleApPowerStateConfigFlag.aidl b/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/current/android/hardware/automotive/vehicle/VehicleApPowerStateConfigFlag.aidl
index 7e48eba..d7b874a 100644
--- a/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/current/android/hardware/automotive/vehicle/VehicleApPowerStateConfigFlag.aidl
+++ b/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/current/android/hardware/automotive/vehicle/VehicleApPowerStateConfigFlag.aidl
@@ -36,5 +36,5 @@
 enum VehicleApPowerStateConfigFlag {
   ENABLE_DEEP_SLEEP_FLAG = 1,
   CONFIG_SUPPORT_TIMER_POWER_ON_FLAG = 2,
-  ENABLE_HIBERNATION_FLAG = 3,
+  ENABLE_HIBERNATION_FLAG = 4,
 }
diff --git a/automotive/vehicle/aidl/android/hardware/automotive/vehicle/VehicleApPowerStateConfigFlag.aidl b/automotive/vehicle/aidl/android/hardware/automotive/vehicle/VehicleApPowerStateConfigFlag.aidl
index 4d8e2f5..8b0190ce 100644
--- a/automotive/vehicle/aidl/android/hardware/automotive/vehicle/VehicleApPowerStateConfigFlag.aidl
+++ b/automotive/vehicle/aidl/android/hardware/automotive/vehicle/VehicleApPowerStateConfigFlag.aidl
@@ -37,5 +37,5 @@
      * (via VehicleApPowerStateShutdownParam#CAN_HIBERNATE or
      *  VehicleApPowerStateShutdownParam#HIBERNATE_IMMEDIATELY flags)
      */
-    ENABLE_HIBERNATION_FLAG = 0x3,
+    ENABLE_HIBERNATION_FLAG = 0x4,
 }
diff --git a/camera/common/1.0/default/HandleImporter.cpp b/camera/common/1.0/default/HandleImporter.cpp
index fbe8686..d2fdf02 100644
--- a/camera/common/1.0/default/HandleImporter.cpp
+++ b/camera/common/1.0/default/HandleImporter.cpp
@@ -18,6 +18,7 @@
 #include "HandleImporter.h"
 
 #include <gralloctypes/Gralloc4.h>
+#include "aidl/android/hardware/graphics/common/Smpte2086.h"
 #include <log/log.h>
 
 namespace android {
@@ -30,6 +31,7 @@
 using aidl::android::hardware::graphics::common::PlaneLayout;
 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;
@@ -127,16 +129,35 @@
 bool isMetadataPesent(const sp<IMapperV4> mapper, const buffer_handle_t& buf,
         MetadataType metadataType) {
     auto buffer = const_cast<native_handle_t*>(buf);
-    mapper->get(buffer, metadataType, [] (const auto& tmpError,
+    bool ret = false;
+    hidl_vec<uint8_t> vec;
+    mapper->get(buffer, metadataType, [&] (const auto& tmpError,
                 const auto& tmpMetadata) {
                     if (tmpError == MapperErrorV4::NONE) {
-                        return tmpMetadata.size() > 0;
+                        vec = tmpMetadata;
                     } else {
                         ALOGE("%s: failed to get metadata %d!", __FUNCTION__, tmpError);
-                        return false;
                     }});
 
-    return false;
+    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) {
diff --git a/camera/device/3.8/Android.bp b/camera/device/3.8/Android.bp
deleted file mode 100644
index c3c2941..0000000
--- a/camera/device/3.8/Android.bp
+++ /dev/null
@@ -1,39 +0,0 @@
-// This file is autogenerated by hidl-gen -Landroidbp.
-
-package {
-    // See: http://go/android-license-faq
-    // A large-scale-change added 'default_applicable_licenses' to import
-    // all of the 'license_kinds' from "hardware_interfaces_license"
-    // to get the below license kinds:
-    //   SPDX-license-identifier-Apache-2.0
-    default_applicable_licenses: ["hardware_interfaces_license"],
-}
-
-hidl_interface {
-    name: "android.hardware.camera.device@3.8",
-    root: "android.hardware",
-    srcs: [
-        "types.hal",
-        "ICameraDevice.hal",
-        "ICameraDeviceCallback.hal",
-        "ICameraDeviceSession.hal",
-    ],
-    interfaces: [
-        "android.hardware.camera.common@1.0",
-        "android.hardware.camera.device@3.2",
-        "android.hardware.camera.device@3.3",
-        "android.hardware.camera.device@3.4",
-        "android.hardware.camera.device@3.5",
-        "android.hardware.camera.device@3.6",
-        "android.hardware.camera.device@3.7",
-        "android.hardware.camera.metadata@3.2",
-        "android.hardware.camera.metadata@3.3",
-        "android.hardware.camera.metadata@3.4",
-        "android.hardware.camera.metadata@3.5",
-        "android.hardware.camera.metadata@3.6",
-        "android.hardware.camera.metadata@3.8",
-        "android.hardware.graphics.common@1.0",
-        "android.hidl.base@1.0",
-    ],
-    gen_java: false,
-}
diff --git a/camera/device/3.8/ICameraDevice.hal b/camera/device/3.8/ICameraDevice.hal
deleted file mode 100644
index 09edb8b..0000000
--- a/camera/device/3.8/ICameraDevice.hal
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (C) 2021 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.camera.device@3.8;
-
-import android.hardware.camera.common@1.0::Status;
-import @3.7::ICameraDevice;
-
-/**
- * Camera device interface
- *
- * Supports the android.hardware.Camera API, and the android.hardware.camera2
- * API at LIMITED or better hardware level.
- *
- * ICameraDevice.open() must return @3.2::ICameraDeviceSession,
- * @3.5::ICameraDeviceSession, @3.6::ICameraDeviceSession,
- * @3.7::ICameraDeviceSession, or @3.8::ICameraDeviceSession.
- */
-interface ICameraDevice extends @3.7::ICameraDevice {
-    /**
-     * turnOnTorchWithStrengthLevel:
-     *
-     * Change the brightness level of the flash unit associated with this camera device
-     * and set it to value in torchStrength. This function also turns ON the torch
-     * with specified torchStrength if the torch is OFF.
-     *
-     * The torchStrength value must be within the valid range i.e. >=1 and
-     * <= FLASH_INFO_STRENGTH_MAXIMUM_LEVEL. Whenever the torch is turned OFF,
-     * the brightness level will reset to FLASH_INFO_STRENGTH_DEFAULT_LEVEL.
-     * When the client calls setTorchMode(ON) after turnOnTorchWithStrengthLevel(N),
-     * the flash unit will have brightness level equal to N. This level does not
-     * represent the real brightness units. It is linear in nature i.e. flashlight
-     * at level 10 is twice as bright as at level 5.
-     *
-     * @param torchStrength Brightness level to be set for the flashlight.
-     *
-     * @return status Status code for the operation, one of:
-     *     OK:
-     *         On a successful change to the torch strength level.
-     *     INTERNAL_ERROR:
-     *         The flash unit cannot be operated due to an unexpected internal
-     *         error.
-     *     CAMERA_IN_USE:
-     *         This status code is returned when:
-     *           - This camera device has been opened, so the torch cannot be
-     *             controlled until it is closed.
-     *           - Due to other camera devices being open, or due to other
-     *             resource constraints, the torch cannot be controlled currently.
-     *     ILLEGAL_ARGUMENT:
-     *         If the torchStrength value is not within the range i.e. < 1 or
-     *         > FLASH_INFO_STRENGTH_MAXIMUM_LEVEL.
-     *     METHOD_NOT_SUPPORTED:
-     *         This status code is returned when:
-     *           - This camera device does not support direct operation of flashlight
-     *             torch mode. The framework must open the camera device and turn
-     *             the torch on through the device interface.
-     *           - This camera device does not have a flash unit.
-     *           - This camera device has flash unit but does not support torch
-     *             strength control.
-     *     CAMERA_DISCONNECTED:
-     *         An external camera device has been disconnected, and is no longer
-     *         available. This camera device interface is now stale, and a new
-     *         instance must be acquired if the device is reconnected. All
-     *         subsequent calls on this interface must return
-     *         CAMERA_DISCONNECTED.
-     *
-     */
-    turnOnTorchWithStrengthLevel(int32_t torchStrength) generates (Status status);
-
-    /**
-     * getTorchStrengthLevel:
-     *
-     * Get current torch strength level.
-     * If the device supports torch strength control, when the torch is OFF the
-     * strength level will reset to default level, so the return
-     * value in this case will be equal to FLASH_INFO_STRENGTH_DEFAULT_LEVEL.
-     *
-     * @return status Status code for the operation, one of:
-     *      OK:
-     *           On success.
-     *      INTERNAL_ERROR:
-     *           An unexpected error occurred and the information is not
-     *           available.
-     *      METHOD_NOT_SUPPORTED:
-     *          This status code is returned when:
-     *            - This camera device does not support direct operation of flashlight
-     *              torch mode. The framework must open the camera device and turn
-     *              the torch on through the device interface.
-     *            - This camera device does not have a flash unit.
-     *            - This camera device has flash unit but does not support torch
-     *              strength control.
-     *
-     * @return torchStrength Current torch strength level.
-     *
-     */
-    getTorchStrengthLevel() generates (Status status, int32_t torchStrength);
-
-     /**
-     * isStreamCombinationSupported_3_8:
-     *
-     * Identical to @3.7::ICameraDevice.isStreamCombinationSupported, except
-     * that it takes a @3.8::StreamConfiguration parameter, which could contain
-     * additional information about a specific 10-bit dynamic range profile or
-     * stream use case.
-     *
-     */
-    isStreamCombinationSupported_3_8(StreamConfiguration streams)
-            generates (Status status, bool queryStatus);
-};
diff --git a/camera/device/3.8/ICameraDeviceCallback.hal b/camera/device/3.8/ICameraDeviceCallback.hal
deleted file mode 100644
index de0775d..0000000
--- a/camera/device/3.8/ICameraDeviceCallback.hal
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2021 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.camera.device@3.8;
-
-import @3.5::ICameraDeviceCallback;
-
-/**
- * Callback methods for the HAL to call into the framework.
- */
-interface ICameraDeviceCallback extends @3.5::ICameraDeviceCallback {
-    /**
-     * Identical to @3.5::ICameraDeviceCallback.notify, except that it takes a
-     * list of @3.8::NotifyMsg which contain readout timestamp in addition
-     * to exposure start timestamp for shutter.
-     *
-     * The readout timestamp is used for the framework to re-time the viewfinder
-     * frames targeted for SurfaceView so that preview jitter can be reduced.
-     */
-    notify_3_8(vec<NotifyMsg> msgs);
-};
diff --git a/camera/device/3.8/ICameraDeviceSession.hal b/camera/device/3.8/ICameraDeviceSession.hal
deleted file mode 100644
index c3aa836..0000000
--- a/camera/device/3.8/ICameraDeviceSession.hal
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2021 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.camera.device@3.8;
-
-import android.hardware.camera.common@1.0::Status;
-import @3.5::StreamConfiguration;
-import @3.7::ICameraDeviceSession;
-import @3.6::HalStreamConfiguration;
-
-/**
- * Camera device active session interface.
- *
- * Obtained via ICameraDevice::open(), this interface contains the methods to
- * configure and request captures from an active camera device.
- */
-interface ICameraDeviceSession extends @3.7::ICameraDeviceSession {
-    /**
-     * configureStreams_3_8:
-     *
-     * Identical to @3.7::ICameraDeviceSession.configureStreams_3_7, except that:
-     *
-     * - The requestedConfiguration allows the camera framework to configure
-     *   10-bit dynamic range profile.
-     * - The requestedConfiguration allows the camera framework to configure
-     *   stream use cases.
-     *
-     * @return status Status code for the operation, one of:
-     *     OK:
-     *         On successful stream configuration.
-     *     INTERNAL_ERROR:
-     *         If there has been a fatal error and the device is no longer
-     *         operational. Only close() can be called successfully by the
-     *         framework after this error is returned.
-     *     ILLEGAL_ARGUMENT:
-     *         If the requested stream configuration is invalid. Some examples
-     *         of invalid stream configurations include:
-     *           - Including more than 1 INPUT stream
-     *           - Not including any OUTPUT streams
-     *           - Including streams with unsupported formats, or an unsupported
-     *             size for that format.
-     *           - Including too many output streams of a certain format.
-     *           - Unsupported rotation configuration
-     *           - Stream sizes/formats don't satisfy the
-     *             StreamConfigurationMode requirements
-     *             for non-NORMAL mode, or the requested operation_mode is not
-     *             supported by the HAL.
-     *           - Unsupported usage flag
-     *           - Unsupported stream groupIds, or unsupported multi-resolution
-     *             input stream.
-     *           - Invalid combination between a 10-bit dynamic range profile
-     *             and none impl. defined 8-bit format for a particular stream.
-     *           - Unsupported stream use case
-     *         The camera service cannot filter out all possible illegal stream
-     *         configurations, since some devices may support more simultaneous
-     *         streams or larger stream resolutions than the minimum required
-     *         for a given camera device hardware level. The HAL must return an
-     *         ILLEGAL_ARGUMENT for any unsupported stream set, and then be
-     *         ready to accept a future valid stream configuration in a later
-     *         configureStreams call.
-     * @return halConfiguration The stream parameters desired by the HAL for
-     *     each stream, including maximum buffers, the usage flags, and the
-     *     override format and dataspace.
-     */
-    configureStreams_3_8(StreamConfiguration requestedConfiguration)
-        generates (Status status, @3.6::HalStreamConfiguration halConfiguration);
-
-    /**
-     * repeatingRequestEnd:
-     *
-     * Notification about the last frame number in a repeating request along with the
-     * ids of all streams included in the repeating request.
-     *
-     * This can be called at any point after 'processCaptureRequest' in response
-     * to camera clients disabling an active repeating request.
-     *
-     * Performance requirements:
-     * The call must not be blocked for extensive periods and should be extremely lightweight. There
-     * must be no frame rate degradation or frame jitter introduced.
-     *
-     * This method must always succeed, even if the device has encountered a
-     * serious error.
-     */
-    repeatingRequestEnd(uint32_t frameNumber, vec<int32_t> streamIds);
-};
diff --git a/camera/device/3.8/types.hal b/camera/device/3.8/types.hal
deleted file mode 100644
index 04a2450..0000000
--- a/camera/device/3.8/types.hal
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Copyright (C) 2021 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.camera.device@3.8;
-
-import @3.2::ErrorMsg;
-import @3.2::CameraMetadata;
-import @3.2::MsgType;
-import @3.2::ShutterMsg;
-import @3.2::CameraMetadata;
-import @3.2::StreamConfigurationMode;
-import @3.7::Stream;
-
-import android.hardware.camera.metadata@3.8::CameraMetadataEnumAndroidRequestAvailableDynamicRangeProfilesMap;
-import android.hardware.camera.metadata@3.8::CameraMetadataEnumAndroidScalerAvailableStreamUseCases;
-
-/**
- * ShutterMsg:
- *
- * Message contents for MsgType::SHUTTER
- *
- * This version extends the @3.2 ShutterMsg with the readout timestamp.
- */
-struct ShutterMsg {
-    /**
-     * The definition of ShutterMsg from prior version.
-     */
-    @3.2::ShutterMsg v3_2;
-
-    /**
-     * Timestamp for the capture readout. This must be in the same time domain
-     * as v3_2.timestamp, and for a rolling shutter sensor, the value must be
-     * v3_2.timestamp + exposureTime + t_crop_top where t_crop_top is the exposure time
-     * skew of the cropped lines on the top.
-     */
-    uint64_t readoutTimestamp;
-};
-
-/**
- * NotifyMsg:
- *
- * The message structure sent to ICameraDevice3Callback::notify()
- *
- * This version extends the @3.2 NotifyMsg with the @3.8 version of ShutterMsg.
- */
-struct NotifyMsg {
-    /**
-     * The message type.
-     */
-    @3.2::MsgType type;
-
-    union Message {
-        /**
-         * Error message contents. Valid if type is MsgType::ERROR
-         */
-        @3.2::ErrorMsg error;
-
-        /**
-         * Shutter message contents. Valid if type is MsgType::SHUTTER
-         */
-        ShutterMsg shutter;
-    } msg;
-};
-
-/**
- * Stream:
- *
- * A descriptor for a single camera input or output stream. A stream is defined
- * by the framework by its buffer resolution and format, and additionally by the
- * HAL with the gralloc usage flags and the maximum in-flight buffer count.
- *
- * This version extends the @3.7 Stream with the dynamic range profile and the
- * stream use case field.
- */
-struct Stream {
-    /**
-     * The definition of Stream from the prior version.
-     */
-    @3.7::Stream v3_7;
-
-    /**
-     * The dynamic range profile for this stream.
-     *
-     * This field is valid and must only be considered for streams with format
-     * android.hardware.graphics.common.PixelFormat.YCBCR_P010 or
-     * android.hardware.graphics.common.PixelFormat.IMPLEMENTATION_DEFINED on devices supporting the
-     * ANDROID_REQUEST_AVAILABLE_CAPABILITIES_DYNAMIC_RANGE_10_BIT capability.
-     *
-     */
-    CameraMetadataEnumAndroidRequestAvailableDynamicRangeProfilesMap dynamicRangeProfile;
-
-    /**
-     * The stream use case describing the stream's purpose
-     *
-     * This flag provides the camera device a hint on what user scenario this
-     * stream is intended for. With this flag, the camera device can optimize
-     * camera pipeline parameters, such as tuning, sensor mode, and ISP settings,
-     * for the intended use case.
-     *
-     * When this field is set to DEFAULT, the camera device should behave in
-     * the same way as in previous HAL versions, and optimize the camera pipeline
-     * based on stream format, data space, usage flag, and other stream properties.
-     *
-     * The HAL reports supported stream use cases in
-     * ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES. If the HAL doesn't support
-     * setting stream use cases, the camera framework leaves this field as
-     * DEFAULT.
-     */
-    CameraMetadataEnumAndroidScalerAvailableStreamUseCases useCase;
-};
-
-/**
- * StreamConfiguration:
- *
- * Identical to @3.7::StreamConfiguration, except that the streams
- * vector contains @3.8::Stream.
- */
-struct StreamConfiguration {
-    /**
-     * An array of camera stream pointers, defining the input/output
-     * configuration for the camera HAL device.
-     */
-    vec<Stream> streams;
-
-    /**
-     * The definition of operation mode from prior version.
-     */
-    @3.2::StreamConfigurationMode operationMode;
-
-    /**
-     * The definition of session parameters from prior version.
-     */
-    @3.2::CameraMetadata sessionParams;
-
-    /**
-     * The definition of stream configuration counter from prior version.
-     */
-    uint32_t streamConfigCounter;
-
-    /**
-     * The definition of multi-resolution input image flag from prior version.
-     */
-    bool multiResolutionInputImage;
-};
diff --git a/camera/metadata/3.8/Android.bp b/camera/metadata/3.8/Android.bp
deleted file mode 100644
index ead9543..0000000
--- a/camera/metadata/3.8/Android.bp
+++ /dev/null
@@ -1,27 +0,0 @@
-// This file is autogenerated by hidl-gen -Landroidbp.
-
-package {
-    // See: http://go/android-license-faq
-    // A large-scale-change added 'default_applicable_licenses' to import
-    // all of the 'license_kinds' from "hardware_interfaces_license"
-    // to get the below license kinds:
-    //   SPDX-license-identifier-Apache-2.0
-    default_applicable_licenses: ["hardware_interfaces_license"],
-}
-
-hidl_interface {
-    name: "android.hardware.camera.metadata@3.8",
-    root: "android.hardware",
-    srcs: [
-        "types.hal",
-    ],
-    interfaces: [
-        "android.hardware.camera.metadata@3.2",
-        "android.hardware.camera.metadata@3.3",
-        "android.hardware.camera.metadata@3.4",
-        "android.hardware.camera.metadata@3.5",
-        "android.hardware.camera.metadata@3.6",
-        "android.hardware.camera.metadata@3.7",
-    ],
-    gen_java: true,
-}
diff --git a/camera/metadata/3.8/types.hal b/camera/metadata/3.8/types.hal
deleted file mode 100644
index 8cc6646..0000000
--- a/camera/metadata/3.8/types.hal
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- * Copyright (C) 2021 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.
- */
-
-/*
- * Autogenerated from camera metadata definitions in
- * /system/media/camera/docs/metadata_definitions.xml
- * *** DO NOT EDIT BY HAND ***
- */
-
-package android.hardware.camera.metadata@3.8;
-
-import android.hardware.camera.metadata@3.2;
-import android.hardware.camera.metadata@3.3;
-import android.hardware.camera.metadata@3.4;
-import android.hardware.camera.metadata@3.5;
-import android.hardware.camera.metadata@3.6;
-import android.hardware.camera.metadata@3.7;
-
-/**
- * Top level hierarchy definitions for camera metadata. *_INFO sections are for
- * the static metadata that can be retrieved without opening the camera device.
- */
-enum CameraMetadataSection : @3.4::CameraMetadataSection {
-    ANDROID_AUTOMOTIVE =
-        android.hardware.camera.metadata@3.4::CameraMetadataSection:ANDROID_SECTION_COUNT,
-
-    ANDROID_AUTOMOTIVE_LENS,
-
-    ANDROID_SECTION_COUNT_3_8,
-
-    VENDOR_SECTION_3_8 = 0x8000,
-
-};
-
-/**
- * Hierarchy positions in enum space. All vendor extension sections must be
- * defined with tag >= VENDOR_SECTION_START
- */
-enum CameraMetadataSectionStart : android.hardware.camera.metadata@3.4::CameraMetadataSectionStart {
-    ANDROID_AUTOMOTIVE_START = CameraMetadataSection:ANDROID_AUTOMOTIVE << 16,
-
-    ANDROID_AUTOMOTIVE_LENS_START = CameraMetadataSection:ANDROID_AUTOMOTIVE_LENS << 16,
-
-    VENDOR_SECTION_START_3_8 = CameraMetadataSection:VENDOR_SECTION_3_8 << 16,
-
-};
-
-/**
- * Main enumeration for defining camera metadata tags added in this revision
- *
- * <p>Partial documentation is included for each tag; for complete documentation, reference
- * '/system/media/camera/docs/docs.html' in the corresponding Android source tree.</p>
- */
-enum CameraMetadataTag : @3.7::CameraMetadataTag {
-    /** android.flash.info.strengthMaximumLevel [static, int32, public]
-     *
-     * <p>Maximum flashlight brightness level.</p>
-     */
-    ANDROID_FLASH_INFO_STRENGTH_MAXIMUM_LEVEL = android.hardware.camera.metadata@3.2::CameraMetadataTag:ANDROID_FLASH_INFO_END,
-
-    /** android.flash.info.strengthDefaultLevel [static, int32, public]
-     *
-     * <p>Default flashlight brightness level to be set via
-     * {android.hardware.camera2.CameraManager#turnOnTorchWithStrengthLevel}.</p>
-     */
-    ANDROID_FLASH_INFO_STRENGTH_DEFAULT_LEVEL,
-
-    ANDROID_FLASH_INFO_END_3_8,
-
-    /** android.request.availableDynamicRangeProfilesMap [static, enum[], ndk_public]
-     *
-     * <p>A map of all available 10-bit dynamic range profiles along with their
-     * capture request constraints.</p>
-     */
-    ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP = android.hardware.camera.metadata@3.4::CameraMetadataTag:ANDROID_REQUEST_END_3_4,
-
-    /** android.request.recommendedTenBitDynamicRangeProfile [static, int64, java_public]
-     *
-     * <p>Recommended 10-bit dynamic range profile.</p>
-     */
-    ANDROID_REQUEST_RECOMMENDED_TEN_BIT_DYNAMIC_RANGE_PROFILE,
-
-    ANDROID_REQUEST_END_3_8,
-
-    /** android.scaler.availableStreamUseCases [static, enum[], public]
-     *
-     * <p>The stream use cases supported by this camera device.</p>
-     */
-    ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES = android.hardware.camera.metadata@3.6::CameraMetadataTag:ANDROID_SCALER_END_3_6,
-
-    ANDROID_SCALER_END_3_8,
-
-    /** android.automotive.location [static, enum, public]
-     *
-     * <p>Location of the cameras on the automotive devices.</p>
-     */
-    ANDROID_AUTOMOTIVE_LOCATION = CameraMetadataSectionStart:ANDROID_AUTOMOTIVE_START,
-
-    ANDROID_AUTOMOTIVE_END_3_8,
-
-    /** android.automotive.lens.facing [static, enum[], public]
-     *
-     * <p>The direction of the camera faces relative to the vehicle body frame and the
-     * passenger seats.</p>
-     */
-    ANDROID_AUTOMOTIVE_LENS_FACING = CameraMetadataSectionStart:ANDROID_AUTOMOTIVE_LENS_START,
-
-    ANDROID_AUTOMOTIVE_LENS_END_3_8,
-
-};
-
-/*
- * Enumeration definitions for the various entries that need them
- */
-
-/** android.control.videoStabilizationMode enumeration values added since v3.2
- * @see ANDROID_CONTROL_VIDEO_STABILIZATION_MODE
- */
-enum CameraMetadataEnumAndroidControlVideoStabilizationMode :
-        @3.2::CameraMetadataEnumAndroidControlVideoStabilizationMode {
-    ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_PREVIEW_STABILIZATION,
-};
-
-/** android.lens.poseReference enumeration values added since v3.5
- * @see ANDROID_LENS_POSE_REFERENCE
- */
-enum CameraMetadataEnumAndroidLensPoseReference :
-        @3.5::CameraMetadataEnumAndroidLensPoseReference {
-    ANDROID_LENS_POSE_REFERENCE_AUTOMOTIVE,
-};
-
-/** android.request.availableCapabilities enumeration values added since v3.6
- * @see ANDROID_REQUEST_AVAILABLE_CAPABILITIES
- */
-enum CameraMetadataEnumAndroidRequestAvailableCapabilities :
-        @3.6::CameraMetadataEnumAndroidRequestAvailableCapabilities {
-    ANDROID_REQUEST_AVAILABLE_CAPABILITIES_DYNAMIC_RANGE_TEN_BIT,
-    ANDROID_REQUEST_AVAILABLE_CAPABILITIES_STREAM_USE_CASE,
-};
-
-/** android.request.availableDynamicRangeProfilesMap enumeration values
- * @see ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP
- */
-enum CameraMetadataEnumAndroidRequestAvailableDynamicRangeProfilesMap : int64_t {
-    ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_STANDARD
-                                                                 = 0x1,
-    ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_HLG10  = 0x2,
-    ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_HDR10  = 0x4,
-    ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_HDR10_PLUS
-                                                                 = 0x8,
-    ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_10B_HDR_REF
-                                                                 = 0x10,
-    ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_10B_HDR_REF_PO
-                                                                 = 0x20,
-    ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_10B_HDR_OEM
-                                                                 = 0x40,
-    ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_10B_HDR_OEM_PO
-                                                                 = 0x80,
-    ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_8B_HDR_REF
-                                                                 = 0x100,
-    ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_8B_HDR_REF_PO
-                                                                 = 0x200,
-    ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_8B_HDR_OEM
-                                                                 = 0x400,
-    ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_8B_HDR_OEM_PO
-                                                                 = 0x800,
-    ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_MAX    = 0x1000,
-};
-
-/** android.scaler.availableRecommendedStreamConfigurations enumeration values added since v3.4
- * @see ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS
- */
-enum CameraMetadataEnumAndroidScalerAvailableRecommendedStreamConfigurations :
-        @3.4::CameraMetadataEnumAndroidScalerAvailableRecommendedStreamConfigurations {
-    ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS_10BIT_OUTPUT
-                                                                 = 0x8,
-    ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS_PUBLIC_END_3_8
-                                                                 = 0x9,
-};
-
-/** android.scaler.availableStreamUseCases enumeration values
- * @see ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES
- */
-enum CameraMetadataEnumAndroidScalerAvailableStreamUseCases : int64_t {
-    ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT           = 0x0,
-    ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW           = 0x1,
-    ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE     = 0x2,
-    ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD      = 0x3,
-    ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL
-                                                                 = 0x4,
-    ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL        = 0x5,
-    ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VENDOR_START      = 0x10000,
-};
-
-/** android.automotive.location enumeration values
- * @see ANDROID_AUTOMOTIVE_LOCATION
- */
-enum CameraMetadataEnumAndroidAutomotiveLocation : uint32_t {
-    ANDROID_AUTOMOTIVE_LOCATION_INTERIOR,
-    ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_OTHER,
-    ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT,
-    ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR,
-    ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT,
-    ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT,
-    ANDROID_AUTOMOTIVE_LOCATION_EXTRA_OTHER,
-    ANDROID_AUTOMOTIVE_LOCATION_EXTRA_FRONT,
-    ANDROID_AUTOMOTIVE_LOCATION_EXTRA_REAR,
-    ANDROID_AUTOMOTIVE_LOCATION_EXTRA_LEFT,
-    ANDROID_AUTOMOTIVE_LOCATION_EXTRA_RIGHT,
-};
-
-/** android.automotive.lens.facing enumeration values
- * @see ANDROID_AUTOMOTIVE_LENS_FACING
- */
-enum CameraMetadataEnumAndroidAutomotiveLensFacing : uint32_t {
-    ANDROID_AUTOMOTIVE_LENS_FACING_EXTERIOR_OTHER,
-    ANDROID_AUTOMOTIVE_LENS_FACING_EXTERIOR_FRONT,
-    ANDROID_AUTOMOTIVE_LENS_FACING_EXTERIOR_REAR,
-    ANDROID_AUTOMOTIVE_LENS_FACING_EXTERIOR_LEFT,
-    ANDROID_AUTOMOTIVE_LENS_FACING_EXTERIOR_RIGHT,
-    ANDROID_AUTOMOTIVE_LENS_FACING_INTERIOR_OTHER,
-    ANDROID_AUTOMOTIVE_LENS_FACING_INTERIOR_SEAT_ROW_1_LEFT,
-    ANDROID_AUTOMOTIVE_LENS_FACING_INTERIOR_SEAT_ROW_1_CENTER,
-    ANDROID_AUTOMOTIVE_LENS_FACING_INTERIOR_SEAT_ROW_1_RIGHT,
-    ANDROID_AUTOMOTIVE_LENS_FACING_INTERIOR_SEAT_ROW_2_LEFT,
-    ANDROID_AUTOMOTIVE_LENS_FACING_INTERIOR_SEAT_ROW_2_CENTER,
-    ANDROID_AUTOMOTIVE_LENS_FACING_INTERIOR_SEAT_ROW_2_RIGHT,
-    ANDROID_AUTOMOTIVE_LENS_FACING_INTERIOR_SEAT_ROW_3_LEFT,
-    ANDROID_AUTOMOTIVE_LENS_FACING_INTERIOR_SEAT_ROW_3_CENTER,
-    ANDROID_AUTOMOTIVE_LENS_FACING_INTERIOR_SEAT_ROW_3_RIGHT,
-};
diff --git a/camera/provider/2.4/vts/functional/Android.bp b/camera/provider/2.4/vts/functional/Android.bp
index 2f24dfd..85e69eb 100644
--- a/camera/provider/2.4/vts/functional/Android.bp
+++ b/camera/provider/2.4/vts/functional/Android.bp
@@ -50,9 +50,7 @@
         "android.hardware.camera.device@3.5",
         "android.hardware.camera.device@3.6",
         "android.hardware.camera.device@3.7",
-        "android.hardware.camera.device@3.8",
         "android.hardware.camera.metadata@3.4",
-        "android.hardware.camera.metadata@3.8",
         "android.hardware.camera.provider@2.4",
         "android.hardware.camera.provider@2.5",
         "android.hardware.camera.provider@2.6",
diff --git a/camera/provider/2.4/vts/functional/VtsHalCameraProviderV2_4TargetTest.cpp b/camera/provider/2.4/vts/functional/VtsHalCameraProviderV2_4TargetTest.cpp
index f89c71d..6866776 100644
--- a/camera/provider/2.4/vts/functional/VtsHalCameraProviderV2_4TargetTest.cpp
+++ b/camera/provider/2.4/vts/functional/VtsHalCameraProviderV2_4TargetTest.cpp
@@ -42,14 +42,9 @@
 #include <android/hardware/camera/device/3.6/ICameraDevice.h>
 #include <android/hardware/camera/device/3.6/ICameraDeviceSession.h>
 #include <android/hardware/camera/device/3.7/ICameraDevice.h>
-#include <android/hardware/camera/device/3.8/ICameraDevice.h>
 #include <android/hardware/camera/device/3.7/ICameraDeviceSession.h>
-#include <android/hardware/camera/device/3.8/ICameraDeviceSession.h>
 #include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
-#include <android/hardware/camera/device/3.8/ICameraDeviceCallback.h>
-#include <android/hardware/camera/device/3.8/ICameraDeviceSession.h>
 #include <android/hardware/camera/metadata/3.4/types.h>
-#include <android/hardware/camera/metadata/3.8/types.h>
 #include <android/hardware/camera/provider/2.4/ICameraProvider.h>
 #include <android/hardware/camera/provider/2.5/ICameraProvider.h>
 #include <android/hardware/camera/provider/2.6/ICameraProvider.h>
@@ -134,10 +129,6 @@
         CameraMetadataEnumAndroidSensorInfoColorFilterArrangement;
 using ::android::hardware::camera::metadata::V3_4::CameraMetadataTag;
 using ::android::hardware::camera::metadata::V3_6::CameraMetadataEnumAndroidSensorPixelMode;
-using ::android::hardware::camera::metadata::V3_8::
-        CameraMetadataEnumAndroidRequestAvailableDynamicRangeProfilesMap;
-using ::android::hardware::camera::metadata::V3_8::
-        CameraMetadataEnumAndroidScalerAvailableStreamUseCases;
 using ::android::hardware::camera::provider::V2_4::ICameraProvider;
 using ::android::hardware::camera::provider::V2_4::ICameraProviderCallback;
 using ::android::hardware::camera::provider::V2_6::CameraIdAndStreamCombination;
@@ -233,8 +224,7 @@
 
 namespace {
     // "device@<version>/legacy/<id>"
-    const char *kDeviceNameRE = "device@([0-9]+\\.[0-9]+)/%s/(.+)";
-    const int CAMERA_DEVICE_API_VERSION_3_8 = 0x308;
+    const char* kDeviceNameRE = "device@([0-9]+\\.[0-9]+)/%s/(.+)";
     const int CAMERA_DEVICE_API_VERSION_3_7 = 0x307;
     const int CAMERA_DEVICE_API_VERSION_3_6 = 0x306;
     const int CAMERA_DEVICE_API_VERSION_3_5 = 0x305;
@@ -242,19 +232,16 @@
     const int CAMERA_DEVICE_API_VERSION_3_3 = 0x303;
     const int CAMERA_DEVICE_API_VERSION_3_2 = 0x302;
     const int CAMERA_DEVICE_API_VERSION_1_0 = 0x100;
-    const char *kHAL3_8 = "3.8";
-    const char *kHAL3_7 = "3.7";
-    const char *kHAL3_6 = "3.6";
-    const char *kHAL3_5 = "3.5";
-    const char *kHAL3_4 = "3.4";
-    const char *kHAL3_3 = "3.3";
-    const char *kHAL3_2 = "3.2";
-    const char *kHAL1_0 = "1.0";
+    const char* kHAL3_7 = "3.7";
+    const char* kHAL3_6 = "3.6";
+    const char* kHAL3_5 = "3.5";
+    const char* kHAL3_4 = "3.4";
+    const char* kHAL3_3 = "3.3";
+    const char* kHAL3_2 = "3.2";
+    const char* kHAL1_0 = "1.0";
 
-    bool matchDeviceName(const hidl_string& deviceName,
-            const hidl_string &providerType,
-            std::string* deviceVersion,
-            std::string* cameraId) {
+    bool matchDeviceName(const hidl_string& deviceName, const hidl_string& providerType,
+                         std::string* deviceVersion, std::string* cameraId) {
         ::android::String8 pattern;
         pattern.appendFormat(kDeviceNameRE, providerType.c_str());
         std::regex e(pattern.string());
@@ -280,9 +267,7 @@
             return -1;
         }
 
-        if (version.compare(kHAL3_8) == 0) {
-            return CAMERA_DEVICE_API_VERSION_3_8;
-        } else if (version.compare(kHAL3_7) == 0) {
+        if (version.compare(kHAL3_7) == 0) {
             return CAMERA_DEVICE_API_VERSION_3_7;
         } else if (version.compare(kHAL3_6) == 0) {
             return CAMERA_DEVICE_API_VERSION_3_6;
@@ -652,7 +637,8 @@
      }
 
      virtual Return<void> processCaptureResult_3_4(
-         const hidl_vec<V3_4::CaptureResult>& /*results*/) override {
+
+             const hidl_vec<V3_4::CaptureResult>& /*results*/) override {
          ALOGI("processCaptureResult_3_4 callback");
          ADD_FAILURE();  // Empty callback should not reach here
          return Void();
@@ -682,44 +668,41 @@
      }
  };
 
-    struct DeviceCb : public V3_8::ICameraDeviceCallback {
-        DeviceCb(CameraHidlTest *parent, int deviceVersion, const camera_metadata_t *staticMeta) :
-                mParent(parent), mDeviceVersion(deviceVersion) {
+    struct DeviceCb : public V3_5::ICameraDeviceCallback {
+        DeviceCb(CameraHidlTest* parent, int deviceVersion, const camera_metadata_t* staticMeta)
+            : mParent(parent), mDeviceVersion(deviceVersion) {
             mStaticMetadata = staticMeta;
         }
 
-        Return<void> processCaptureResult_3_4(
-                const hidl_vec<V3_4::CaptureResult>& results) override;
+        Return<void> processCaptureResult_3_4(const hidl_vec<V3_4::CaptureResult>& results) override;
         Return<void> processCaptureResult(const hidl_vec<CaptureResult>& results) override;
         Return<void> notify(const hidl_vec<NotifyMsg>& msgs) override;
-        Return<void> notify_3_8(const hidl_vec<V3_8::NotifyMsg>& msgs) override;
 
-        Return<void> requestStreamBuffers(
-                const hidl_vec<V3_5::BufferRequest>& bufReqs,
-                requestStreamBuffers_cb _hidl_cb) override;
+        Return<void> requestStreamBuffers(const hidl_vec<V3_5::BufferRequest>& bufReqs,
+                                          requestStreamBuffers_cb _hidl_cb) override;
 
         Return<void> returnStreamBuffers(const hidl_vec<StreamBuffer>& buffers) override;
 
         void setCurrentStreamConfig(const hidl_vec<V3_4::Stream>& streams,
-                const hidl_vec<V3_2::HalStream>& halStreams);
+                                     const hidl_vec<V3_2::HalStream>& halStreams);
 
         void waitForBuffersReturned();
 
       private:
         bool processCaptureResultLocked(const CaptureResult& results,
-                hidl_vec<PhysicalCameraMetadata> physicalCameraMetadata);
+                                        hidl_vec<PhysicalCameraMetadata> physicalCameraMetadata);
         Return<void> notifyHelper(const hidl_vec<NotifyMsg>& msgs,
-                const std::vector<std::pair<bool, nsecs_t>>& readoutTimestamps);
+                                  const std::vector<std::pair<bool, nsecs_t>>& readoutTimestamps);
 
-        CameraHidlTest *mParent; // Parent object
+        CameraHidlTest* mParent;  // Parent object
         int mDeviceVersion;
         android::hardware::camera::common::V1_0::helper::CameraMetadata mStaticMetadata;
         bool hasOutstandingBuffersLocked();
 
         /* members for requestStreamBuffers() and returnStreamBuffers()*/
-        std::mutex mLock; // protecting members below
-        bool                      mUseHalBufManager = false;
-        hidl_vec<V3_4::Stream>    mStreams;
+        std::mutex mLock;  // protecting members below
+        bool mUseHalBufManager = false;
+        hidl_vec<V3_4::Stream> mStreams;
         hidl_vec<V3_2::HalStream> mHalStreams;
         uint64_t mNextBufferId = 1;
         using OutstandingBuffers = std::unordered_map<uint64_t, hidl_handle>;
@@ -814,20 +797,18 @@
                       sp<provider::V2_5::ICameraProvider>* provider2_5 /*out*/,
                       sp<provider::V2_6::ICameraProvider>* provider2_6 /*out*/,
                       sp<provider::V2_7::ICameraProvider>* provider2_7 /*out*/);
-    void castSession(const sp<ICameraDeviceSession> &session, int32_t deviceVersion,
-            sp<device::V3_3::ICameraDeviceSession> *session3_3 /*out*/,
-            sp<device::V3_4::ICameraDeviceSession> *session3_4 /*out*/,
-            sp<device::V3_5::ICameraDeviceSession> *session3_5 /*out*/,
-            sp<device::V3_6::ICameraDeviceSession> *session3_6 /*out*/,
-            sp<device::V3_7::ICameraDeviceSession> *session3_7 /*out*/,
-            sp<device::V3_8::ICameraDeviceSession> *session3_8 /*out*/);
+    void castSession(const sp<ICameraDeviceSession>& session, int32_t deviceVersion,
+                     sp<device::V3_3::ICameraDeviceSession>* session3_3 /*out*/,
+                     sp<device::V3_4::ICameraDeviceSession>* session3_4 /*out*/,
+                     sp<device::V3_5::ICameraDeviceSession>* session3_5 /*out*/,
+                     sp<device::V3_6::ICameraDeviceSession>* session3_6 /*out*/,
+                     sp<device::V3_7::ICameraDeviceSession>* session3_7 /*out*/);
     void castInjectionSession(
             const sp<ICameraDeviceSession>& session,
             sp<device::V3_7::ICameraInjectionSession>* injectionSession3_7 /*out*/);
     void castDevice(const sp<device::V3_2::ICameraDevice>& device, int32_t deviceVersion,
                     sp<device::V3_5::ICameraDevice>* device3_5 /*out*/,
-                    sp<device::V3_7::ICameraDevice>* device3_7 /*out*/,
-                    sp<device::V3_8::ICameraDevice>* device3_8 /*out*/);
+                    sp<device::V3_7::ICameraDevice>* device3_7 /*out*/);
     void createStreamConfiguration(
             const ::android::hardware::hidl_vec<V3_2::Stream>& streams3_2,
             StreamConfigurationMode configMode,
@@ -857,16 +838,6 @@
                              uint32_t* partialResultCount /*out*/, bool* useHalBufManager /*out*/,
                              sp<DeviceCb>* outCb /*out*/, uint32_t streamConfigCounter,
                              bool maxResolution);
-    void configureStreams3_8(const std::string& name, int32_t deviceVersion,
-                             sp<ICameraProvider> provider, PixelFormat format,
-                             sp<device::V3_8::ICameraDeviceSession>* session3_8 /*out*/,
-                             V3_2::Stream* previewStream /*out*/,
-                             device::V3_6::HalStreamConfiguration* halStreamConfig /*out*/,
-                             bool* supportsPartialResults /*out*/,
-                             uint32_t* partialResultCount /*out*/, bool* useHalBufManager /*out*/,
-                             sp<DeviceCb>* outCb /*out*/, uint32_t streamConfigCounter,
-                             bool maxResolution,
-                             CameraMetadataEnumAndroidRequestAvailableDynamicRangeProfilesMap prof);
 
     void configurePreviewStreams3_4(const std::string &name, int32_t deviceVersion,
             sp<ICameraProvider> provider,
@@ -947,9 +918,6 @@
     static bool isDepthOnly(const camera_metadata_t* staticMeta);
 
     static bool isUltraHighResolution(const camera_metadata_t* staticMeta);
-    static void get10BitDynamicRangeProfiles(const camera_metadata_t* staticMeta,
-        std::vector<CameraMetadataEnumAndroidRequestAvailableDynamicRangeProfilesMap> *profiles);
-    static bool is10BitDynamicRangeCapable(const camera_metadata_t* staticMeta);
 
     static Status getAvailableOutputStreams(const camera_metadata_t* staticMeta,
                                             std::vector<AvailableStream>& outputStreams,
@@ -1130,10 +1098,6 @@
                 expectedPhysicalResults(extraPhysicalResult) {}
     };
 
-    static void verify10BitMetadata(HandleImporter& importer,
-            const InFlightRequest& request,
-            CameraMetadataEnumAndroidRequestAvailableDynamicRangeProfilesMap profile);
-
     // Map from frame number to the in-flight request state
     typedef ::android::KeyedVector<uint32_t, InFlightRequest*> InFlightMap;
 
@@ -1564,32 +1528,6 @@
     }
 }
 
-Return<void> CameraHidlTest::DeviceCb::notify_3_8(
-        const hidl_vec<V3_8::NotifyMsg>& msgs) {
-    hidl_vec<NotifyMsg> msgs3_2;
-    std::vector<std::pair<bool, nsecs_t>> readoutTimestamps;
-
-    nsecs_t count = msgs.size();
-    msgs3_2.resize(count);
-    readoutTimestamps.resize(count);
-
-    for (size_t i = 0; i < count; i++) {
-        msgs3_2[i].type = msgs[i].type;
-        switch (msgs[i].type) {
-            case MsgType::ERROR:
-                msgs3_2[i].msg.error = msgs[i].msg.error;
-                readoutTimestamps[i] = {false, 0};
-                break;
-            case MsgType::SHUTTER:
-                msgs3_2[i].msg.shutter = msgs[i].msg.shutter.v3_2;
-                readoutTimestamps[i] = {true, msgs[i].msg.shutter.readoutTimestamp};
-                break;
-        }
-    }
-
-    return notifyHelper(msgs3_2, readoutTimestamps);
-}
-
 Return<void> CameraHidlTest::DeviceCb::notify(
         const hidl_vec<NotifyMsg>& messages) {
     std::vector<std::pair<bool, nsecs_t>> readoutTimestamps;
@@ -2082,7 +2020,6 @@
     for (const auto& name : cameraDeviceNames) {
         int deviceVersion = getCameraDeviceVersion(name, mProviderType);
         switch (deviceVersion) {
-            case CAMERA_DEVICE_API_VERSION_3_8:
             case CAMERA_DEVICE_API_VERSION_3_7:
             case CAMERA_DEVICE_API_VERSION_3_6:
             case CAMERA_DEVICE_API_VERSION_3_5:
@@ -2127,7 +2064,6 @@
     for (const auto& name : cameraDeviceNames) {
         int deviceVersion = getCameraDeviceVersion(name, mProviderType);
         switch (deviceVersion) {
-            case CAMERA_DEVICE_API_VERSION_3_8:
             case CAMERA_DEVICE_API_VERSION_3_7:
             case CAMERA_DEVICE_API_VERSION_3_6:
             case CAMERA_DEVICE_API_VERSION_3_5:
@@ -2869,7 +2805,6 @@
     for (const auto& name : cameraDeviceNames) {
         int deviceVersion = getCameraDeviceVersion(name, mProviderType);
         switch (deviceVersion) {
-            case CAMERA_DEVICE_API_VERSION_3_8:
             case CAMERA_DEVICE_API_VERSION_3_7:
             case CAMERA_DEVICE_API_VERSION_3_6:
             case CAMERA_DEVICE_API_VERSION_3_5:
@@ -2957,7 +2892,6 @@
     for (const auto& name : cameraDeviceNames) {
         int deviceVersion = getCameraDeviceVersion(name, mProviderType);
         switch (deviceVersion) {
-            case CAMERA_DEVICE_API_VERSION_3_8:
             case CAMERA_DEVICE_API_VERSION_3_7:
             case CAMERA_DEVICE_API_VERSION_3_6:
             case CAMERA_DEVICE_API_VERSION_3_5:
@@ -3018,137 +2952,6 @@
     }
 }
 
-// Verify that the torch strength level can be set and retrieved successfully.
-TEST_P(CameraHidlTest, turnOnTorchWithStrengthLevel) {
-    hidl_vec<hidl_string> cameraDeviceNames = getCameraDeviceNames(mProvider);
-    bool torchControlSupported = false;
-    bool torchStrengthControlSupported = false;
-    Return<void> ret;
-
-    ret = mProvider->isSetTorchModeSupported([&](auto status, bool support) {
-        ALOGI("isSetTorchModeSupported returns status:%d supported:%d", (int)status, support);
-        ASSERT_EQ(Status::OK, status);
-        torchControlSupported = support;
-    });
-
-    sp<TorchProviderCb> cb = new TorchProviderCb(this);
-    Return<Status> returnStatus = mProvider->setCallback(cb);
-    ASSERT_TRUE(returnStatus.isOk());
-    ASSERT_EQ(Status::OK, returnStatus);
-
-    for (const auto& name : cameraDeviceNames) {
-        int deviceVersion = getCameraDeviceVersion(name, mProviderType);
-        int32_t defaultLevel;
-        switch (deviceVersion) {
-            case CAMERA_DEVICE_API_VERSION_3_8: {
-                ::android::sp<::android::hardware::camera::device::V3_8::ICameraDevice> device3_8;
-                ALOGI("%s: Testing camera device %s", __FUNCTION__, name.c_str());
-                ret = mProvider->getCameraDeviceInterface_V3_x(
-                        name, [&](auto status, const auto& device) {
-                            ASSERT_EQ(Status::OK, status);
-                            ASSERT_NE(device, nullptr);
-                            auto castResult = device::V3_8::ICameraDevice::castFrom(device);
-                            ASSERT_TRUE(castResult.isOk());
-                            device3_8 = castResult;
-                        });
-                ASSERT_TRUE(ret.isOk());
-
-                ret = device3_8->getCameraCharacteristics([&] (auto s, const auto& chars) {
-                    ASSERT_EQ(Status::OK, s);
-                    const camera_metadata_t* staticMeta =
-                            reinterpret_cast<const camera_metadata_t*>(chars.data());
-                    ASSERT_NE(nullptr, staticMeta);
-                    torchStrengthControlSupported = isTorchStrengthControlSupported(staticMeta);
-                    camera_metadata_ro_entry entry;
-                    int rc = find_camera_metadata_ro_entry(staticMeta,
-                            ANDROID_FLASH_INFO_STRENGTH_DEFAULT_LEVEL, &entry);
-                    if (torchStrengthControlSupported) {
-                        ASSERT_EQ(rc, 0);
-                        ASSERT_GT(entry.count, 0);
-                        defaultLevel = *entry.data.i32;
-                        ALOGI("Default level is:%d", defaultLevel);
-                    }
-                });
-                ASSERT_TRUE(ret.isOk());
-                // If torchStrengthControl is supported, torchControlSupported should be true.
-                if (torchStrengthControlSupported) {
-                    ASSERT_TRUE(torchControlSupported);
-                }
-                mTorchStatus = TorchModeStatus::NOT_AVAILABLE;
-                returnStatus = device3_8->turnOnTorchWithStrengthLevel(2);
-                ASSERT_TRUE(returnStatus.isOk());
-                // Method_not_supported check
-                if (!torchStrengthControlSupported) {
-                    ALOGI("Torch strength control not supported.");
-                    ASSERT_EQ(Status::METHOD_NOT_SUPPORTED, returnStatus);
-                } else {
-                    ASSERT_EQ(Status::OK, returnStatus);
-                    if (returnStatus == Status::OK) {
-                        {
-                            std::unique_lock<std::mutex> l(mTorchLock);
-                            while (TorchModeStatus::NOT_AVAILABLE == mTorchStatus) {
-                                auto timeout = std::chrono::system_clock::now() +
-                                        std::chrono::seconds(kTorchTimeoutSec);
-                                ASSERT_NE(std::cv_status::timeout, mTorchCond.wait_until(l,
-                                        timeout));
-                            }
-                            ASSERT_EQ(TorchModeStatus::AVAILABLE_ON, mTorchStatus);
-                            mTorchStatus = TorchModeStatus::NOT_AVAILABLE;
-                        }
-                        ALOGI("getTorchStrengthLevel: Testing");
-                        ret = device3_8->getTorchStrengthLevel([&]
-                                (auto status, const auto& strengthLevel) {
-                                    ASSERT_TRUE(ret.isOk());
-                                    ASSERT_EQ(Status::OK, status);
-                                    ALOGI("Torch strength level is : %d", strengthLevel);
-                                    ASSERT_EQ(strengthLevel, 2);
-                                });
-                        // Turn OFF the torch and verify torch strength level is reset to default level.
-                        ALOGI("Testing torch strength level reset after turning the torch OFF.");
-                        returnStatus = device3_8->setTorchMode(TorchMode::OFF);
-                        ASSERT_TRUE(returnStatus.isOk());
-                        ASSERT_EQ(Status::OK, returnStatus);
-                        {
-                            std::unique_lock<std::mutex> l(mTorchLock);
-                            while (TorchModeStatus::NOT_AVAILABLE == mTorchStatus) {
-                                auto timeout = std::chrono::system_clock::now() +
-                                        std::chrono::seconds(kTorchTimeoutSec);
-                                ASSERT_NE(std::cv_status::timeout, mTorchCond.wait_until(l,
-                                        timeout));
-                            }
-                            ASSERT_EQ(TorchModeStatus::AVAILABLE_OFF, mTorchStatus);
-                        }
-                        ret = device3_8->getTorchStrengthLevel([&]
-                                (auto status, const auto& strengthLevel) {
-                                    ASSERT_TRUE(ret.isOk());
-                                    ASSERT_EQ(Status::OK, status);
-                                    ALOGI("Torch strength level after turning OFF torch is : %d",
-                                            strengthLevel);
-                                    ASSERT_EQ(strengthLevel, defaultLevel);
-                                });
-                    }
-                }
-            }
-            break;
-            case CAMERA_DEVICE_API_VERSION_3_7:
-            case CAMERA_DEVICE_API_VERSION_3_6:
-            case CAMERA_DEVICE_API_VERSION_3_5:
-            case CAMERA_DEVICE_API_VERSION_3_4:
-            case CAMERA_DEVICE_API_VERSION_3_3:
-            case CAMERA_DEVICE_API_VERSION_3_2:
-            case CAMERA_DEVICE_API_VERSION_1_0: {
-                ALOGI("Torch strength control feature not supported.");
-            }
-            break;
-            default: {
-                ALOGI("Invalid device version.");
-                ADD_FAILURE();
-            }
-            break;
-        }
-    }
-}
-
 //In case it is supported verify that torch can be enabled.
 //Check for corresponding toch callbacks as well.
 TEST_P(CameraHidlTest, setTorchMode) {
@@ -3170,7 +2973,6 @@
     for (const auto& name : cameraDeviceNames) {
         int deviceVersion = getCameraDeviceVersion(name, mProviderType);
         switch (deviceVersion) {
-            case CAMERA_DEVICE_API_VERSION_3_8:
             case CAMERA_DEVICE_API_VERSION_3_7:
             case CAMERA_DEVICE_API_VERSION_3_6:
             case CAMERA_DEVICE_API_VERSION_3_5:
@@ -3299,7 +3101,6 @@
     for (const auto& name : cameraDeviceNames) {
         int deviceVersion = getCameraDeviceVersion(name, mProviderType);
         switch (deviceVersion) {
-            case CAMERA_DEVICE_API_VERSION_3_8:
             case CAMERA_DEVICE_API_VERSION_3_7:
             case CAMERA_DEVICE_API_VERSION_3_6:
             case CAMERA_DEVICE_API_VERSION_3_5:
@@ -3367,7 +3168,6 @@
     for (const auto& name : cameraDeviceNames) {
         int deviceVersion = getCameraDeviceVersion(name, mProviderType);
         switch (deviceVersion) {
-            case CAMERA_DEVICE_API_VERSION_3_8:
             case CAMERA_DEVICE_API_VERSION_3_7:
             case CAMERA_DEVICE_API_VERSION_3_6:
             case CAMERA_DEVICE_API_VERSION_3_5:
@@ -3401,13 +3201,10 @@
                 sp<device::V3_5::ICameraDeviceSession> sessionV3_5;
                 sp<device::V3_6::ICameraDeviceSession> sessionV3_6;
                 sp<device::V3_7::ICameraDeviceSession> sessionV3_7;
-                sp<device::V3_8::ICameraDeviceSession> sessionV3_8;
-                castSession(session, deviceVersion, &sessionV3_3,
-                        &sessionV3_4, &sessionV3_5, &sessionV3_6,
-                        &sessionV3_7, &sessionV3_8);
-                if (deviceVersion == CAMERA_DEVICE_API_VERSION_3_8) {
-                    ASSERT_TRUE(sessionV3_8.get() != nullptr);
-                } else if (deviceVersion == CAMERA_DEVICE_API_VERSION_3_7) {
+                castSession(session, deviceVersion, &sessionV3_3, &sessionV3_4, &sessionV3_5,
+                            &sessionV3_6, &sessionV3_7);
+
+                if (deviceVersion == CAMERA_DEVICE_API_VERSION_3_7) {
                     ASSERT_TRUE(sessionV3_7.get() != nullptr);
                 } else if (deviceVersion == CAMERA_DEVICE_API_VERSION_3_6) {
                     ASSERT_TRUE(sessionV3_6.get() != nullptr);
@@ -3417,7 +3214,7 @@
                     ASSERT_TRUE(sessionV3_4.get() != nullptr);
                 } else if (deviceVersion == CAMERA_DEVICE_API_VERSION_3_3) {
                     ASSERT_TRUE(sessionV3_3.get() != nullptr);
-                } else { //V3_2
+                } else {  // V3_2
                     ASSERT_TRUE(sessionV3_3.get() == nullptr);
                     ASSERT_TRUE(sessionV3_4.get() == nullptr);
                     ASSERT_TRUE(sessionV3_5.get() == nullptr);
@@ -3473,7 +3270,6 @@
     for (const auto& name : cameraDeviceNames) {
         int deviceVersion = getCameraDeviceVersion(name, mProviderType);
         switch (deviceVersion) {
-            case CAMERA_DEVICE_API_VERSION_3_8:
             case CAMERA_DEVICE_API_VERSION_3_7:
             case CAMERA_DEVICE_API_VERSION_3_6:
             case CAMERA_DEVICE_API_VERSION_3_5:
@@ -3575,17 +3371,14 @@
         sp<device::V3_5::ICameraDeviceSession> session3_5;
         sp<device::V3_6::ICameraDeviceSession> session3_6;
         sp<device::V3_7::ICameraDeviceSession> session3_7;
-        sp<device::V3_8::ICameraDeviceSession> session3_8;
         sp<device::V3_2::ICameraDevice> cameraDevice;
         sp<device::V3_5::ICameraDevice> cameraDevice3_5;
         sp<device::V3_7::ICameraDevice> cameraDevice3_7;
-        sp<device::V3_8::ICameraDevice> cameraDevice3_8;
         openEmptyDeviceSession(name, mProvider,
                 &session /*out*/, &staticMeta /*out*/, &cameraDevice /*out*/);
-        castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5,
-                &session3_6, &session3_7, &session3_8);
-        castDevice(cameraDevice, deviceVersion, &cameraDevice3_5, &cameraDevice3_7,
-                &cameraDevice3_8);
+        castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5, &session3_6,
+                    &session3_7);
+        castDevice(cameraDevice, deviceVersion, &cameraDevice3_5, &cameraDevice3_7);
 
         outputStreams.clear();
         ASSERT_EQ(Status::OK, getAvailableOutputStreams(staticMeta, outputStreams));
@@ -3681,11 +3474,9 @@
         sp<device::V3_5::ICameraDeviceSession> session3_5;
         sp<device::V3_6::ICameraDeviceSession> session3_6;
         sp<device::V3_7::ICameraDeviceSession> session3_7;
-        sp<device::V3_8::ICameraDeviceSession> session3_8;
         sp<device::V3_2::ICameraDevice> cameraDevice;
         sp<device::V3_5::ICameraDevice> cameraDevice3_5;
         sp<device::V3_7::ICameraDevice> cameraDevice3_7;
-        sp<device::V3_8::ICameraDevice> cameraDevice3_8;
         ::android::hardware::camera::device::V3_7::StreamConfiguration config3_7;
         ::android::hardware::camera::device::V3_5::StreamConfiguration config3_5;
         ::android::hardware::camera::device::V3_4::StreamConfiguration config3_4;
@@ -3722,9 +3513,8 @@
             openEmptyDeviceSession(name, mProvider2_6, &cti.session /*out*/,
                                    &cti.staticMeta /*out*/, &cti.cameraDevice /*out*/);
             castSession(cti.session, deviceVersion, &cti.session3_3, &cti.session3_4,
-                        &cti.session3_5, &cti.session3_6, &cti.session3_7, &cti.session3_8);
-            castDevice(cti.cameraDevice, deviceVersion, &cti.cameraDevice3_5, &cti.cameraDevice3_7,
-                    &cti.cameraDevice3_8);
+                        &cti.session3_5, &cti.session3_6, &cti.session3_7);
+            castDevice(cti.cameraDevice, deviceVersion, &cti.cameraDevice3_5, &cti.cameraDevice3_7);
 
             outputStreams.clear();
             ASSERT_EQ(Status::OK, getMandatoryConcurrentStreams(cti.staticMeta, &outputStreams));
@@ -3853,17 +3643,14 @@
         sp<device::V3_5::ICameraDeviceSession> session3_5;
         sp<device::V3_6::ICameraDeviceSession> session3_6;
         sp<device::V3_7::ICameraDeviceSession> session3_7;
-        sp<device::V3_8::ICameraDeviceSession> session3_8;
         sp<device::V3_2::ICameraDevice> cameraDevice;
         sp<device::V3_5::ICameraDevice> cameraDevice3_5;
         sp<device::V3_7::ICameraDevice> cameraDevice3_7;
-        sp<device::V3_8::ICameraDevice> cameraDevice3_8;
         openEmptyDeviceSession(name, mProvider, &session /*out*/, &staticMeta /*out*/,
                 &cameraDevice /*out*/);
-        castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5,
-                &session3_6, &session3_7, &session3_8);
-        castDevice(cameraDevice, deviceVersion, &cameraDevice3_5, &cameraDevice3_7,
-                &cameraDevice3_8);
+        castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5, &session3_6,
+                    &session3_7);
+        castDevice(cameraDevice, deviceVersion, &cameraDevice3_5, &cameraDevice3_7);
 
         outputStreams.clear();
         ASSERT_EQ(Status::OK, getAvailableOutputStreams(staticMeta, outputStreams));
@@ -4069,17 +3856,14 @@
         sp<device::V3_5::ICameraDeviceSession> session3_5;
         sp<device::V3_6::ICameraDeviceSession> session3_6;
         sp<device::V3_7::ICameraDeviceSession> session3_7;
-        sp<device::V3_8::ICameraDeviceSession> session3_8;
         sp<device::V3_2::ICameraDevice> cameraDevice;
         sp<device::V3_5::ICameraDevice> cameraDevice3_5;
         sp<device::V3_7::ICameraDevice> cameraDevice3_7;
-        sp<device::V3_8::ICameraDevice> cameraDevice3_8;
         openEmptyDeviceSession(name, mProvider, &session /*out*/, &staticMeta /*out*/,
                 &cameraDevice /*out*/);
-        castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5,
-                &session3_6, &session3_7, &session3_8);
-        castDevice(cameraDevice, deviceVersion, &cameraDevice3_5, &cameraDevice3_7,
-                &cameraDevice3_8);
+        castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5, &session3_6,
+                    &session3_7);
+        castDevice(cameraDevice, deviceVersion, &cameraDevice3_5, &cameraDevice3_7);
 
         Status rc = isZSLModeAvailable(staticMeta);
         if (Status::METHOD_NOT_SUPPORTED == rc) {
@@ -4258,10 +4042,9 @@
         sp<device::V3_5::ICameraDeviceSession> session3_5;
         sp<device::V3_6::ICameraDeviceSession> session3_6;
         sp<device::V3_7::ICameraDeviceSession> session3_7;
-        sp<device::V3_8::ICameraDeviceSession> session3_8;
         openEmptyDeviceSession(name, mProvider, &session /*out*/, &staticMetaBuffer /*out*/);
-        castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5,
-                &session3_6, &session3_7, &session3_8);
+        castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5, &session3_6,
+                    &session3_7);
         if (deviceVersion == CAMERA_DEVICE_API_VERSION_3_4) {
             ASSERT_NE(session3_4, nullptr);
         } else {
@@ -4400,17 +4183,14 @@
         sp<device::V3_5::ICameraDeviceSession> session3_5;
         sp<device::V3_6::ICameraDeviceSession> session3_6;
         sp<device::V3_7::ICameraDeviceSession> session3_7;
-        sp<device::V3_8::ICameraDeviceSession> session3_8;
         sp<device::V3_2::ICameraDevice> cameraDevice;
         sp<device::V3_5::ICameraDevice> cameraDevice3_5;
         sp<device::V3_7::ICameraDevice> cameraDevice3_7;
-        sp<device::V3_8::ICameraDevice> cameraDevice3_8;
         openEmptyDeviceSession(name, mProvider, &session /*out*/, &staticMeta /*out*/,
                 &cameraDevice /*out*/);
-        castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5,
-                &session3_6, &session3_7, &session3_8);
-        castDevice(cameraDevice, deviceVersion, &cameraDevice3_5, &cameraDevice3_7,
-                &cameraDevice3_8);
+        castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5, &session3_6,
+                    &session3_7);
+        castDevice(cameraDevice, deviceVersion, &cameraDevice3_5, &cameraDevice3_7);
 
         // Check if camera support depth only
         if (isDepthOnly(staticMeta)) {
@@ -4537,17 +4317,14 @@
         sp<device::V3_5::ICameraDeviceSession> session3_5;
         sp<device::V3_6::ICameraDeviceSession> session3_6;
         sp<device::V3_7::ICameraDeviceSession> session3_7;
-        sp<device::V3_8::ICameraDeviceSession> session3_8;
         sp<device::V3_2::ICameraDevice> cameraDevice;
         sp<device::V3_5::ICameraDevice> cameraDevice3_5;
         sp<device::V3_7::ICameraDevice> cameraDevice3_7;
-        sp<device::V3_8::ICameraDevice> cameraDevice3_8;
         openEmptyDeviceSession(name, mProvider, &session /*out*/, &staticMeta /*out*/,
                 &cameraDevice /*out*/);
-        castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5,
-                &session3_6, &session3_7, &session3_8);
-        castDevice(cameraDevice, deviceVersion, &cameraDevice3_5, &cameraDevice3_7,
-                &cameraDevice3_8);
+        castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5, &session3_6,
+                    &session3_7);
+        castDevice(cameraDevice, deviceVersion, &cameraDevice3_5, &cameraDevice3_7);
 
         Status rc = isConstrainedModeAvailable(staticMeta);
         if (Status::METHOD_NOT_SUPPORTED == rc) {
@@ -4820,17 +4597,14 @@
         sp<device::V3_5::ICameraDeviceSession> session3_5;
         sp<device::V3_6::ICameraDeviceSession> session3_6;
         sp<device::V3_7::ICameraDeviceSession> session3_7;
-        sp<device::V3_8::ICameraDeviceSession> session3_8;
         sp<device::V3_2::ICameraDevice> cameraDevice;
         sp<device::V3_5::ICameraDevice> cameraDevice3_5;
         sp<device::V3_7::ICameraDevice> cameraDevice3_7;
-        sp<device::V3_8::ICameraDevice> cameraDevice3_8;
         openEmptyDeviceSession(name, mProvider, &session /*out*/, &staticMeta /*out*/,
                 &cameraDevice /*out*/);
-        castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5,
-                &session3_6, &session3_7, &session3_8);
-        castDevice(cameraDevice, deviceVersion, &cameraDevice3_5, &cameraDevice3_7,
-                &cameraDevice3_8);
+        castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5, &session3_6,
+                    &session3_7);
+        castDevice(cameraDevice, deviceVersion, &cameraDevice3_5, &cameraDevice3_7);
 
         // Check if camera support depth only
         if (isDepthOnly(staticMeta)) {
@@ -5069,28 +4843,6 @@
             ASSERT_NE(inflightReq.resultOutputBuffers.size(), 0u);
             ASSERT_EQ(testStream.id, inflightReq.resultOutputBuffers[0].buffer.streamId);
 
-            // For camera device 3.8 or newer, shutterReadoutTimestamp must be
-            // available, and it must be >= shutterTimestamp + exposureTime, and
-            // < shutterTimestamp + exposureTime + rollingShutterSkew / 2.
-            if (deviceVersion >= CAMERA_DEVICE_API_VERSION_3_8) {
-                ASSERT_TRUE(inflightReq.shutterReadoutTimestampValid);
-                ASSERT_FALSE(inflightReq.collectedResult.isEmpty());
-                if (inflightReq.collectedResult.exists(ANDROID_SENSOR_EXPOSURE_TIME)) {
-                    camera_metadata_entry_t exposureTimeResult = inflightReq.collectedResult.find(
-                            ANDROID_SENSOR_EXPOSURE_TIME);
-                    nsecs_t exposureToReadout =
-                            inflightReq.shutterReadoutTimestamp - inflightReq.shutterTimestamp;
-                    ASSERT_GE(exposureToReadout, exposureTimeResult.data.i64[0]);
-                    if (inflightReq.collectedResult.exists(ANDROID_SENSOR_ROLLING_SHUTTER_SKEW)) {
-                        camera_metadata_entry_t rollingShutterSkew =
-                                inflightReq.collectedResult.find(
-                                        ANDROID_SENSOR_ROLLING_SHUTTER_SKEW);
-                        ASSERT_LT(exposureToReadout, exposureTimeResult.data.i64[0] +
-                                                             rollingShutterSkew.data.i64[0] / 2);
-                    }
-                }
-            }
-
             request.frameNumber++;
             // Empty settings should be supported after the first call
             // for repeating requests.
@@ -5114,20 +4866,6 @@
         ASSERT_EQ(Status::OK, status);
         ASSERT_EQ(numRequestProcessed, 1u);
 
-        if (deviceVersion >= CAMERA_DEVICE_API_VERSION_3_8) {
-            sp<device::V3_3::ICameraDeviceSession> session3_3;
-            sp<device::V3_4::ICameraDeviceSession> session3_4;
-            sp<device::V3_5::ICameraDeviceSession> session3_5;
-            sp<device::V3_6::ICameraDeviceSession> session3_6;
-            sp<device::V3_7::ICameraDeviceSession> session3_7;
-            sp<device::V3_8::ICameraDeviceSession> session3_8;
-            castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5,
-                    &session3_6, &session3_7, &session3_8);
-            ASSERT_TRUE(session3_8.get() != nullptr);
-            hidl_vec<int32_t> streamIds = { halStreamConfig.streams[0].id };
-            session3_8->repeatingRequestEnd(request.frameNumber, streamIds);
-        }
-
         {
             std::unique_lock<std::mutex> l(mLock);
             while (!inflightReq.errorCodeValid &&
@@ -5153,196 +4891,6 @@
     }
 }
 
-TEST_P(CameraHidlTest, processCaptureRequestPreviewStabilization) {
-    std::unordered_map<std::string, nsecs_t> cameraDeviceToTimeLag;
-    processPreviewStabilizationCaptureRequestInternal(/*previewStabilizationOn*/ false,
-                                                      cameraDeviceToTimeLag);
-    processPreviewStabilizationCaptureRequestInternal(/*previewStabilizationOn*/ true,
-                                                      cameraDeviceToTimeLag);
-}
-
-void CameraHidlTest::processPreviewStabilizationCaptureRequestInternal(
-        bool previewStabilizationOn,
-        // Used as output when preview stabilization is off, as output when its
-        // on.
-        std::unordered_map<std::string, nsecs_t>& cameraDeviceToTimeLag) {
-    hidl_vec<hidl_string> cameraDeviceNames = getCameraDeviceNames(mProvider);
-    AvailableStream streamThreshold = {kMaxPreviewWidth, kMaxPreviewHeight,
-                                       static_cast<int32_t>(PixelFormat::IMPLEMENTATION_DEFINED)};
-    uint64_t bufferId = 1;
-    uint32_t frameNumber = 1;
-    ::android::hardware::hidl_vec<uint8_t> settings;
-
-    for (const auto& name : cameraDeviceNames) {
-        int deviceVersion = getCameraDeviceVersion(name, mProviderType);
-        if (deviceVersion == CAMERA_DEVICE_API_VERSION_1_0) {
-            continue;
-        } else if (deviceVersion <= 0) {
-            ALOGE("%s: Unsupported device version %d", __func__, deviceVersion);
-            ADD_FAILURE();
-            return;
-        }
-
-        if (!supportsPreviewStabilization(name, mProvider)) {
-            ALOGI(" %s Camera device %s doesn't support preview stabilization, skipping", __func__,
-                  name.c_str());
-            continue;
-        }
-
-        if (deviceVersion < CAMERA_DEVICE_API_VERSION_3_8) {
-            ALOGE("%s: device version < 3.8 must not advertise preview stabilization,"
-                  " camera metadata validation will fail",
-                  __func__);
-            ADD_FAILURE();
-        }
-
-        V3_2::Stream testStream;
-        HalStreamConfiguration halStreamConfig;
-        sp<ICameraDeviceSession> session;
-        sp<DeviceCb> cb;
-        bool supportsPartialResults = false;
-        bool useHalBufManager = false;
-        uint32_t partialResultCount = 0;
-        configureSingleStream(name, deviceVersion, mProvider, &streamThreshold,
-                              GRALLOC1_CONSUMER_USAGE_HWCOMPOSER, RequestTemplate::PREVIEW,
-                              &session /*out*/, &testStream /*out*/, &halStreamConfig /*out*/,
-                              &supportsPartialResults /*out*/, &partialResultCount /*out*/,
-                              &useHalBufManager /*out*/, &cb /*out*/);
-
-        std::shared_ptr<ResultMetadataQueue> resultQueue;
-        auto resultQueueRet =
-                session->getCaptureResultMetadataQueue([&resultQueue](const auto& descriptor) {
-                    resultQueue = std::make_shared<ResultMetadataQueue>(descriptor);
-                    if (!resultQueue->isValid() || resultQueue->availableToWrite() <= 0) {
-                        ALOGE("%s: HAL returns empty result metadata fmq,"
-                              " not use it",
-                              __func__);
-                        resultQueue = nullptr;
-                        // Don't use the queue onwards.
-                    }
-                });
-        ASSERT_TRUE(resultQueueRet.isOk());
-
-        InFlightRequest inflightReq = {1, false, supportsPartialResults, partialResultCount,
-                                       resultQueue};
-
-        Return<void> ret;
-        android::hardware::camera::common::V1_0::helper::CameraMetadata defaultSettings;
-        ret = session->constructDefaultRequestSettings(
-                RequestTemplate::PREVIEW, [&](auto status, const auto& req) {
-                    ASSERT_EQ(Status::OK, status);
-                    const camera_metadata_t* metadata =
-                            reinterpret_cast<const camera_metadata_t*>(req.data());
-                    defaultSettings = metadata;
-                    settings = req;
-                });
-        ASSERT_TRUE(ret.isOk());
-        android::status_t metadataRet = ::android::OK;
-        uint8_t videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
-        if (previewStabilizationOn) {
-            videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_PREVIEW_STABILIZATION;
-            metadataRet = defaultSettings.update(ANDROID_CONTROL_VIDEO_STABILIZATION_MODE,
-                                                 &videoStabilizationMode, 1);
-        } else {
-            metadataRet = defaultSettings.update(ANDROID_CONTROL_VIDEO_STABILIZATION_MODE,
-                                                 &videoStabilizationMode, 1);
-        }
-        ASSERT_EQ(metadataRet, ::android::OK);
-        hidl_handle buffer_handle;
-        StreamBuffer outputBuffer;
-        if (useHalBufManager) {
-            outputBuffer = {halStreamConfig.streams[0].id,
-                            /*bufferId*/ 0,
-                            buffer_handle,
-                            BufferStatus::OK,
-                            nullptr,
-                            nullptr};
-        } else {
-            allocateGraphicBuffer(
-                    testStream.width, testStream.height,
-                    /* We don't look at halStreamConfig.streams[0].consumerUsage
-                     * since that is 0 for output streams
-                     */
-                    android_convertGralloc1To0Usage(halStreamConfig.streams[0].producerUsage,
-                                                    GRALLOC1_CONSUMER_USAGE_HWCOMPOSER),
-                    halStreamConfig.streams[0].overrideFormat, &buffer_handle);
-            outputBuffer = {halStreamConfig.streams[0].id,
-                            bufferId,
-                            buffer_handle,
-                            BufferStatus::OK,
-                            nullptr,
-                            nullptr};
-        }
-        ::android::hardware::hidl_vec<StreamBuffer> outputBuffers = {outputBuffer};
-        StreamBuffer emptyInputBuffer = {-1, 0, nullptr, BufferStatus::ERROR, nullptr, nullptr};
-        CaptureRequest request = {frameNumber, 0 /* fmqSettingsSize */, settings, emptyInputBuffer,
-                                  outputBuffers};
-
-        {
-            std::unique_lock<std::mutex> l(mLock);
-            mInflightMap.clear();
-            mInflightMap.add(frameNumber, &inflightReq);
-        }
-
-        Status status = Status::INTERNAL_ERROR;
-        uint32_t numRequestProcessed = 0;
-        hidl_vec<BufferCache> cachesToRemove;
-        Return<void> returnStatus = session->processCaptureRequest(
-                {request}, cachesToRemove, [&status, &numRequestProcessed](auto s, uint32_t n) {
-                    status = s;
-                    numRequestProcessed = n;
-                });
-        ASSERT_TRUE(returnStatus.isOk());
-        ASSERT_EQ(Status::OK, status);
-        ASSERT_EQ(numRequestProcessed, 1u);
-
-        {
-            std::unique_lock<std::mutex> l(mLock);
-            while (!inflightReq.errorCodeValid &&
-                   ((0 < inflightReq.numBuffersLeft) || (!inflightReq.haveResultMetadata))) {
-                auto timeout = std::chrono::system_clock::now() +
-                               std::chrono::seconds(kStreamBufferTimeoutSec);
-                ASSERT_NE(std::cv_status::timeout, mResultCondition.wait_until(l, timeout));
-            }
-
-            ASSERT_FALSE(inflightReq.errorCodeValid);
-            ASSERT_NE(inflightReq.resultOutputBuffers.size(), 0u);
-            ASSERT_EQ(testStream.id, inflightReq.resultOutputBuffers[0].buffer.streamId);
-            ASSERT_TRUE(inflightReq.shutterReadoutTimestampValid);
-            nsecs_t readoutTimestamp = inflightReq.shutterReadoutTimestamp;
-
-            if (previewStabilizationOn) {
-                // Here we collect the time difference between the buffer ready
-                // timestamp - notify readout timestamp.
-                // timeLag = buffer ready timestamp - notify readout timestamp.
-                // timeLag(previewStabilization) must be <=
-                //        timeLag(stabilization off) + 1 frame duration.
-                auto it = cameraDeviceToTimeLag.find(name.c_str());
-                camera_metadata_entry e;
-                e = inflightReq.collectedResult.find(ANDROID_SENSOR_FRAME_DURATION);
-                ASSERT_TRUE(e.count > 0);
-                nsecs_t frameDuration = e.data.i64[0];
-                ASSERT_TRUE(it != cameraDeviceToTimeLag.end());
-
-                nsecs_t previewStabOnLagTime =
-                        inflightReq.resultOutputBuffers[0].timeStamp - readoutTimestamp;
-                ASSERT_TRUE(previewStabOnLagTime <= (it->second + frameDuration));
-            } else {
-                // Fill in the buffer ready timestamp - notify timestamp;
-                cameraDeviceToTimeLag[std::string(name.c_str())] =
-                        inflightReq.resultOutputBuffers[0].timeStamp - readoutTimestamp;
-            }
-        }
-
-        if (useHalBufManager) {
-            verifyBuffersReturned(session, deviceVersion, testStream.id, cb);
-        }
-
-        ret = session->close();
-        ASSERT_TRUE(ret.isOk());
-    }
-}
-
 // Generate and verify a multi-camera capture request
 TEST_P(CameraHidlTest, processMultiCaptureRequestPreview) {
     hidl_vec<hidl_string> cameraDeviceNames = getCameraDeviceNames(mProvider);
@@ -5771,188 +5319,6 @@
     }
 }
 
-// Generate and verify 10-bit dynamic range request
-TEST_P(CameraHidlTest, process10BitDynamicRangeRequest) {
-    hidl_vec<hidl_string> cameraDeviceNames = getCameraDeviceNames(mProvider);
-    uint64_t bufferId = 1;
-    uint32_t frameNumber = 1;
-    ::android::hardware::hidl_vec<uint8_t> settings;
-
-    for (const auto& name : cameraDeviceNames) {
-        int deviceVersion = getCameraDeviceVersion(name, mProviderType);
-        if (deviceVersion < CAMERA_DEVICE_API_VERSION_3_8) {
-            continue;
-        }
-        std::string version, deviceId;
-        ASSERT_TRUE(::matchDeviceName(name, mProviderType, &version, &deviceId));
-        camera_metadata_t* staticMeta;
-        Return<void> ret;
-        sp<ICameraDeviceSession> session;
-        openEmptyDeviceSession(name, mProvider, &session, &staticMeta);
-        if (!is10BitDynamicRangeCapable(staticMeta)) {
-            free_camera_metadata(staticMeta);
-            ret = session->close();
-            ASSERT_TRUE(ret.isOk());
-            continue;
-        }
-        std::vector<CameraMetadataEnumAndroidRequestAvailableDynamicRangeProfilesMap> profileList;
-        get10BitDynamicRangeProfiles(staticMeta, &profileList);
-        ASSERT_FALSE(profileList.empty());
-
-        android::hardware::camera::common::V1_0::helper::CameraMetadata defaultSettings;
-        ret = session->constructDefaultRequestSettings(
-                RequestTemplate::STILL_CAPTURE,
-                [&defaultSettings](auto status, const auto& req) mutable {
-                    ASSERT_EQ(Status::OK, status);
-
-                    const camera_metadata_t* metadata =
-                            reinterpret_cast<const camera_metadata_t*>(req.data());
-                    size_t expectedSize = req.size();
-                    int result = validate_camera_metadata_structure(metadata, &expectedSize);
-                    ASSERT_TRUE((result == 0) || (result == CAMERA_METADATA_VALIDATION_SHIFTED));
-
-                    size_t entryCount = get_camera_metadata_entry_count(metadata);
-                    ASSERT_GT(entryCount, 0u);
-                    defaultSettings = metadata;
-                });
-        ASSERT_TRUE(ret.isOk());
-
-        const camera_metadata_t* settingsBuffer = defaultSettings.getAndLock();
-        settings.setToExternal(
-                reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(settingsBuffer)),
-                get_camera_metadata_size(settingsBuffer));
-        overrideRotateAndCrop(&settings);
-
-        free_camera_metadata(staticMeta);
-        ret = session->close();
-        ASSERT_TRUE(ret.isOk());
-        V3_6::HalStreamConfiguration halStreamConfig;
-        bool supportsPartialResults = false;
-        bool useHalBufManager = false;
-        uint32_t partialResultCount = 0;
-        V3_2::Stream previewStream;
-        sp<device::V3_8::ICameraDeviceSession> session3_8;
-        sp<DeviceCb> cb;
-        for (const auto& profile : profileList) {
-            configureStreams3_8(name, deviceVersion, mProvider, PixelFormat::IMPLEMENTATION_DEFINED,
-                                &session3_8, &previewStream, &halStreamConfig,
-                                &supportsPartialResults, &partialResultCount, &useHalBufManager,
-                                &cb, 0, /*maxResolution*/ false, profile);
-            ASSERT_NE(session3_8, nullptr);
-
-            std::shared_ptr<ResultMetadataQueue> resultQueue;
-            auto resultQueueRet = session3_8->getCaptureResultMetadataQueue(
-                    [&resultQueue](const auto& descriptor) {
-                        resultQueue = std::make_shared<ResultMetadataQueue>(descriptor);
-                        if (!resultQueue->isValid() || resultQueue->availableToWrite() <= 0) {
-                            ALOGE("%s: HAL returns empty result metadata fmq,"
-                                  " not use it",
-                                  __func__);
-                            resultQueue = nullptr;
-                            // Don't use the queue onwards.
-                        }
-                    });
-            ASSERT_TRUE(resultQueueRet.isOk());
-
-            std::vector<hidl_handle> graphicBuffers;
-            graphicBuffers.reserve(halStreamConfig.streams.size());
-            ::android::hardware::hidl_vec<StreamBuffer> outputBuffers;
-            outputBuffers.resize(halStreamConfig.streams.size());
-            InFlightRequest inflightReq = {static_cast<ssize_t>(halStreamConfig.streams.size()),
-                                           false,
-                                           supportsPartialResults,
-                                           partialResultCount,
-                                           std::unordered_set<std::string>(),
-                                           resultQueue};
-
-            size_t k = 0;
-            for (const auto& halStream : halStreamConfig.streams) {
-                hidl_handle buffer_handle;
-                if (useHalBufManager) {
-                    outputBuffers[k] = {halStream.v3_4.v3_3.v3_2.id,
-                                        0,
-                                        buffer_handle,
-                                        BufferStatus::OK,
-                                        nullptr,
-                                        nullptr};
-                } else {
-                    allocateGraphicBuffer(
-                            previewStream.width, previewStream.height,
-                            android_convertGralloc1To0Usage(halStream.v3_4.v3_3.v3_2.producerUsage,
-                                                            halStream.v3_4.v3_3.v3_2.consumerUsage),
-                            halStream.v3_4.v3_3.v3_2.overrideFormat, &buffer_handle);
-
-                    graphicBuffers.push_back(buffer_handle);
-                    outputBuffers[k] = {halStream.v3_4.v3_3.v3_2.id,
-                                        bufferId,
-                                        buffer_handle,
-                                        BufferStatus::OK,
-                                        nullptr,
-                                        nullptr};
-                    bufferId++;
-                }
-                k++;
-            }
-
-            StreamBuffer emptyInputBuffer = {-1, 0, nullptr, BufferStatus::ERROR, nullptr, nullptr};
-            V3_4::CaptureRequest request3_4;
-            request3_4.v3_2.frameNumber = frameNumber;
-            request3_4.v3_2.fmqSettingsSize = 0;
-            request3_4.v3_2.settings = settings;
-            request3_4.v3_2.inputBuffer = emptyInputBuffer;
-            request3_4.v3_2.outputBuffers = outputBuffers;
-            V3_7::CaptureRequest request3_7;
-            request3_7.v3_4 = request3_4;
-            request3_7.inputWidth = 0;
-            request3_7.inputHeight = 0;
-
-            {
-                std::unique_lock<std::mutex> l(mLock);
-                mInflightMap.clear();
-                mInflightMap.add(frameNumber, &inflightReq);
-            }
-
-            Status stat = Status::INTERNAL_ERROR;
-            uint32_t numRequestProcessed = 0;
-            hidl_vec<BufferCache> cachesToRemove;
-            Return<void> returnStatus = session3_8->processCaptureRequest_3_7(
-                    {request3_7}, cachesToRemove,
-                    [&stat, &numRequestProcessed](auto s, uint32_t n) {
-                        stat = s;
-                        numRequestProcessed = n;
-                    });
-            ASSERT_TRUE(returnStatus.isOk());
-            ASSERT_EQ(Status::OK, stat);
-            ASSERT_EQ(numRequestProcessed, 1u);
-
-            {
-                std::unique_lock<std::mutex> l(mLock);
-                while (!inflightReq.errorCodeValid &&
-                       ((0 < inflightReq.numBuffersLeft) || (!inflightReq.haveResultMetadata))) {
-                    auto timeout = std::chrono::system_clock::now() +
-                                   std::chrono::seconds(kStreamBufferTimeoutSec);
-                    ASSERT_NE(std::cv_status::timeout, mResultCondition.wait_until(l, timeout));
-                }
-
-                ASSERT_FALSE(inflightReq.errorCodeValid);
-                ASSERT_NE(inflightReq.resultOutputBuffers.size(), 0u);
-                verify10BitMetadata(mHandleImporter, inflightReq, profile);
-            }
-            if (useHalBufManager) {
-                hidl_vec<int32_t> streamIds(halStreamConfig.streams.size());
-                for (size_t i = 0; i < streamIds.size(); i++) {
-                    streamIds[i] = halStreamConfig.streams[i].v3_4.v3_3.v3_2.id;
-                }
-                session3_8->signalStreamFlush(streamIds, /*streamConfigCounter*/ 0);
-                cb->waitForBuffersReturned();
-            }
-
-            ret = session3_8->close();
-            ASSERT_TRUE(ret.isOk());
-        }
-    }
-}
-
 // Generate and verify a burst containing alternating sensor sensitivity values
 TEST_P(CameraHidlTest, processCaptureRequestBurstISO) {
     hidl_vec<hidl_string> cameraDeviceNames = getCameraDeviceNames(mProvider);
@@ -5982,8 +5348,8 @@
         camera_metadata_entry_t hwLevel = staticMeta.find(ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL);
         ASSERT_TRUE(0 < hwLevel.count);
         if (ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED == hwLevel.data.u8[0] ||
-                ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL == hwLevel.data.u8[0]) {
-            //Limited/External devices can skip this test
+            ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL == hwLevel.data.u8[0]) {
+            // Limited/External devices can skip this test
             ret = session->close();
             ASSERT_TRUE(ret.isOk());
             continue;
@@ -6946,134 +6312,6 @@
     }
 }
 
-// Verify that  valid stream use cases can be configured successfully, and invalid use cases
-// fail stream configuration.
-TEST_P(CameraHidlTest, configureStreamsUseCases) {
-    hidl_vec<hidl_string> cameraDeviceNames = getCameraDeviceNames(mProvider);
-
-    for (const auto& name : cameraDeviceNames) {
-        int deviceVersion = getCameraDeviceVersion(name, mProviderType);
-        if (deviceVersion < CAMERA_DEVICE_API_VERSION_3_8) {
-            continue;
-        }
-
-        camera_metadata_t* staticMeta;
-        Return<void> ret;
-        sp<ICameraDeviceSession> session;
-        sp<device::V3_3::ICameraDeviceSession> session3_3;
-        sp<device::V3_4::ICameraDeviceSession> session3_4;
-        sp<device::V3_5::ICameraDeviceSession> session3_5;
-        sp<device::V3_6::ICameraDeviceSession> session3_6;
-        sp<device::V3_7::ICameraDeviceSession> session3_7;
-        sp<device::V3_8::ICameraDeviceSession> session3_8;
-        sp<device::V3_2::ICameraDevice> cameraDevice;
-        sp<device::V3_5::ICameraDevice> cameraDevice3_5;
-        sp<device::V3_7::ICameraDevice> cameraDevice3_7;
-        sp<device::V3_8::ICameraDevice> cameraDevice3_8;
-        openEmptyDeviceSession(name, mProvider, &session /*out*/, &staticMeta /*out*/,
-                &cameraDevice /*out*/);
-        castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5,
-                &session3_6, &session3_7, &session3_8);
-        ASSERT_NE(nullptr, session3_8);
-        castDevice(cameraDevice, deviceVersion, &cameraDevice3_5, &cameraDevice3_7,
-                   &cameraDevice3_8);
-        ASSERT_NE(nullptr, cameraDevice3_8);
-
-        // Check if camera support depth only
-        if (isDepthOnly(staticMeta)) {
-            free_camera_metadata(staticMeta);
-            ret = session->close();
-            ASSERT_TRUE(ret.isOk());
-            continue;
-        }
-
-        std::vector<AvailableStream> outputPreviewStreams;
-        AvailableStream previewThreshold = {kMaxPreviewWidth, kMaxPreviewHeight,
-                static_cast<int32_t>(PixelFormat::YCBCR_420_888)};
-        ASSERT_EQ(Status::OK, getAvailableOutputStreams(staticMeta, outputPreviewStreams,
-                &previewThreshold));
-        ASSERT_NE(0u, outputPreviewStreams.size());
-
-        // Combine valid and invalid stream use cases
-        std::vector<int64_t> useCases(kMandatoryUseCases);
-        useCases.push_back(ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL + 1);
-
-        std::vector<int64_t> supportedUseCases;
-        camera_metadata_ro_entry entry;
-        auto retcode = find_camera_metadata_ro_entry(staticMeta,
-                ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES, &entry);
-        if ((0 == retcode) && (entry.count > 0)) {
-            supportedUseCases.insert(supportedUseCases.end(), entry.data.i64,
-                    entry.data.i64 + entry.count);
-        } else {
-            supportedUseCases.push_back(ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT);
-        }
-        free_camera_metadata(staticMeta);
-
-        ::android::hardware::hidl_vec<V3_8::Stream> streams3_8(1);
-        streams3_8[0].v3_7.groupId = -1;
-        streams3_8[0].v3_7.sensorPixelModesUsed = {
-                CameraMetadataEnumAndroidSensorPixelMode::ANDROID_SENSOR_PIXEL_MODE_DEFAULT};
-        streams3_8[0].v3_7.v3_4.bufferSize = 0;
-        streams3_8[0].v3_7.v3_4.v3_2.id = 0;
-        streams3_8[0].v3_7.v3_4.v3_2.streamType = StreamType::OUTPUT;
-        streams3_8[0].v3_7.v3_4.v3_2.width = static_cast<uint32_t>(outputPreviewStreams[0].width);
-        streams3_8[0].v3_7.v3_4.v3_2.height = static_cast<uint32_t>(outputPreviewStreams[0].height);
-        streams3_8[0].v3_7.v3_4.v3_2.format =
-                static_cast<PixelFormat>(outputPreviewStreams[0].format);
-        streams3_8[0].v3_7.v3_4.v3_2.usage = GRALLOC1_CONSUMER_USAGE_CPU_READ;
-        streams3_8[0].v3_7.v3_4.v3_2.dataSpace = 0;
-        streams3_8[0].v3_7.v3_4.v3_2.rotation = StreamRotation::ROTATION_0;
-        streams3_8[0].dynamicRangeProfile =
-                static_cast<CameraMetadataEnumAndroidRequestAvailableDynamicRangeProfilesMap>(
-                        ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_STANDARD);
-
-        uint32_t streamConfigCounter = 0;
-        ::android::hardware::camera::device::V3_8::StreamConfiguration config3_8;
-        RequestTemplate reqTemplate = RequestTemplate::STILL_CAPTURE;
-        ret = session3_8->constructDefaultRequestSettings(reqTemplate,
-                                        [&config3_8](auto status, const auto& req) {
-                                                    ASSERT_EQ(Status::OK, status);
-                                                    config3_8.sessionParams = req;
-                                                });
-        ASSERT_TRUE(ret.isOk());
-
-        for (int64_t useCase : useCases) {
-            bool useCaseSupported = std::find(supportedUseCases.begin(),
-                    supportedUseCases.end(), useCase) != supportedUseCases.end();
-
-            streams3_8[0].useCase =
-                    static_cast<CameraMetadataEnumAndroidScalerAvailableStreamUseCases>(useCase);
-            config3_8.streams = streams3_8;
-            config3_8.operationMode = StreamConfigurationMode::NORMAL_MODE;
-            config3_8.streamConfigCounter = streamConfigCounter;
-            config3_8.multiResolutionInputImage = false;
-            ret = cameraDevice3_8->isStreamCombinationSupported_3_8(
-                    config3_8, [&useCaseSupported](Status s, bool combStatus) {
-                        ASSERT_TRUE((Status::OK == s) || (Status::METHOD_NOT_SUPPORTED == s));
-                        if (Status::OK == s) {
-                            ASSERT_EQ(combStatus, useCaseSupported);
-                        }
-                    });
-            ASSERT_TRUE(ret.isOk());
-
-            ret = session3_8->configureStreams_3_8(
-                              config3_8,
-                              [&](Status s, device::V3_6::HalStreamConfiguration halConfig) {
-                                  if (useCaseSupported) {
-                                      ASSERT_EQ(Status::OK, s);
-                                      ASSERT_EQ(1u, halConfig.streams.size());
-                                  } else {
-                                      ASSERT_EQ(Status::ILLEGAL_ARGUMENT, s);
-                                  }
-                              });
-            ASSERT_TRUE(ret.isOk());
-        }
-        ret = session3_8->close();
-        ASSERT_TRUE(ret.isOk());
-    }
-}
-
 // Retrieve all valid output stream resolutions from the camera
 // static characteristics.
 Status CameraHidlTest::getAvailableOutputStreams(const camera_metadata_t* staticMeta,
@@ -7736,9 +6974,8 @@
     sp<device::V3_4::ICameraDeviceSession> session3_4;
     sp<device::V3_5::ICameraDeviceSession> session3_5;
     sp<device::V3_6::ICameraDeviceSession> session3_6;
-    sp<device::V3_8::ICameraDeviceSession> session3_8;
     castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5, &session3_6,
-                session3_7, &session3_8);
+                session3_7);
     ASSERT_NE(nullptr, (*session3_7).get());
 
     *useHalBufManager = false;
@@ -7786,8 +7023,7 @@
     ASSERT_TRUE(deviceVersion >= CAMERA_DEVICE_API_VERSION_3_7);
     sp<device::V3_5::ICameraDevice> cameraDevice3_5 = nullptr;
     sp<device::V3_7::ICameraDevice> cameraDevice3_7 = nullptr;
-    sp<device::V3_8::ICameraDevice> cameraDevice3_8 = nullptr;
-    castDevice(device3_x, deviceVersion, &cameraDevice3_5, &cameraDevice3_7, &cameraDevice3_8);
+    castDevice(device3_x, deviceVersion, &cameraDevice3_5, &cameraDevice3_7);
     ASSERT_NE(cameraDevice3_7, nullptr);
     bool supported = false;
     ret = cameraDevice3_7->isStreamCombinationSupported_3_7(
@@ -7820,153 +7056,6 @@
     ASSERT_TRUE(ret.isOk());
 }
 
-// Configure streams
-void CameraHidlTest::configureStreams3_8(
-        const std::string& name, int32_t deviceVersion, sp<ICameraProvider> provider,
-        PixelFormat format, sp<device::V3_8::ICameraDeviceSession>* session3_8 /*out*/,
-        V3_2::Stream* previewStream /*out*/,
-        device::V3_6::HalStreamConfiguration* halStreamConfig /*out*/,
-        bool* supportsPartialResults /*out*/, uint32_t* partialResultCount /*out*/,
-        bool* useHalBufManager /*out*/, sp<DeviceCb>* outCb /*out*/, uint32_t streamConfigCounter,
-        bool maxResolution,
-        CameraMetadataEnumAndroidRequestAvailableDynamicRangeProfilesMap prof) {
-    ASSERT_NE(nullptr, session3_8);
-    ASSERT_NE(nullptr, halStreamConfig);
-    ASSERT_NE(nullptr, previewStream);
-    ASSERT_NE(nullptr, supportsPartialResults);
-    ASSERT_NE(nullptr, partialResultCount);
-    ASSERT_NE(nullptr, useHalBufManager);
-    ASSERT_NE(nullptr, outCb);
-    ASSERT_TRUE(deviceVersion >= CAMERA_DEVICE_API_VERSION_3_8);
-
-    std::vector<AvailableStream> outputStreams;
-    ::android::sp<ICameraDevice> device3_x;
-    ALOGI("configureStreams: Testing camera device %s", name.c_str());
-    Return<void> ret;
-    ret = provider->getCameraDeviceInterface_V3_x(name, [&](auto status, const auto& device) {
-        ALOGI("getCameraDeviceInterface_V3_x returns status:%d", (int)status);
-        ASSERT_EQ(Status::OK, status);
-        ASSERT_NE(device, nullptr);
-        device3_x = device;
-    });
-    ASSERT_TRUE(ret.isOk());
-
-    camera_metadata_t* staticMeta;
-    ret = device3_x->getCameraCharacteristics([&](Status s, CameraMetadata metadata) {
-        ASSERT_EQ(Status::OK, s);
-        staticMeta =
-                clone_camera_metadata(reinterpret_cast<const camera_metadata_t*>(metadata.data()));
-        ASSERT_NE(nullptr, staticMeta);
-    });
-    ASSERT_TRUE(ret.isOk());
-
-    camera_metadata_ro_entry entry;
-    auto status =
-            find_camera_metadata_ro_entry(staticMeta, ANDROID_REQUEST_PARTIAL_RESULT_COUNT, &entry);
-    if ((0 == status) && (entry.count > 0)) {
-        *partialResultCount = entry.data.i32[0];
-        *supportsPartialResults = (*partialResultCount > 1);
-    }
-
-    sp<DeviceCb> cb = new DeviceCb(this, deviceVersion, staticMeta);
-    sp<ICameraDeviceSession> session;
-    ret = device3_x->open(cb, [&session](auto status, const auto& newSession) {
-        ALOGI("device::open returns status:%d", (int)status);
-        ASSERT_EQ(Status::OK, status);
-        ASSERT_NE(newSession, nullptr);
-        session = newSession;
-    });
-    ASSERT_TRUE(ret.isOk());
-    *outCb = cb;
-
-    sp<device::V3_3::ICameraDeviceSession> session3_3;
-    sp<device::V3_4::ICameraDeviceSession> session3_4;
-    sp<device::V3_5::ICameraDeviceSession> session3_5;
-    sp<device::V3_6::ICameraDeviceSession> session3_6;
-    sp<device::V3_7::ICameraDeviceSession> session3_7;
-    castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5, &session3_6,
-                &session3_7, session3_8);
-    ASSERT_NE(nullptr, (*session3_8).get());
-
-    *useHalBufManager = false;
-    status = find_camera_metadata_ro_entry(
-            staticMeta, ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION, &entry);
-    if ((0 == status) && (entry.count == 1)) {
-        *useHalBufManager = (entry.data.u8[0] ==
-                             ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
-    }
-
-    outputStreams.clear();
-    Size maxSize;
-    auto rc = getMaxOutputSizeForFormat(staticMeta, format, &maxSize, maxResolution);
-    ASSERT_EQ(Status::OK, rc);
-    free_camera_metadata(staticMeta);
-
-    ::android::hardware::hidl_vec<V3_8::Stream> streams3_8(1);
-    streams3_8[0].v3_7.groupId = -1;
-    streams3_8[0].v3_7.sensorPixelModesUsed = {
-            CameraMetadataEnumAndroidSensorPixelMode::ANDROID_SENSOR_PIXEL_MODE_DEFAULT};
-    streams3_8[0].v3_7.v3_4.bufferSize = 0;
-    streams3_8[0].v3_7.v3_4.v3_2.id = 0;
-    streams3_8[0].v3_7.v3_4.v3_2.streamType = StreamType::OUTPUT;
-    streams3_8[0].v3_7.v3_4.v3_2.width = static_cast<uint32_t>(maxSize.width);
-    streams3_8[0].v3_7.v3_4.v3_2.height = static_cast<uint32_t>(maxSize.height);
-    streams3_8[0].v3_7.v3_4.v3_2.format = static_cast<PixelFormat>(format);
-    streams3_8[0].v3_7.v3_4.v3_2.usage = GRALLOC1_CONSUMER_USAGE_CPU_READ;
-    streams3_8[0].v3_7.v3_4.v3_2.dataSpace = 0;
-    streams3_8[0].v3_7.v3_4.v3_2.rotation = StreamRotation::ROTATION_0;
-    streams3_8[0].dynamicRangeProfile = prof;
-
-    ::android::hardware::camera::device::V3_8::StreamConfiguration config3_8;
-    config3_8.streams = streams3_8;
-    config3_8.operationMode = StreamConfigurationMode::NORMAL_MODE;
-    config3_8.streamConfigCounter = streamConfigCounter;
-    config3_8.multiResolutionInputImage = false;
-    RequestTemplate reqTemplate = RequestTemplate::STILL_CAPTURE;
-    ret = (*session3_8)
-                  ->constructDefaultRequestSettings(reqTemplate,
-                                                    [&config3_8](auto status, const auto& req) {
-                                                        ASSERT_EQ(Status::OK, status);
-                                                        config3_8.sessionParams = req;
-                                                    });
-    ASSERT_TRUE(ret.isOk());
-
-    sp<device::V3_5::ICameraDevice> cameraDevice3_5 = nullptr;
-    sp<device::V3_7::ICameraDevice> cameraDevice3_7 = nullptr;
-    sp<device::V3_8::ICameraDevice> cameraDevice3_8 = nullptr;
-    castDevice(device3_x, deviceVersion, &cameraDevice3_5, &cameraDevice3_7, &cameraDevice3_8);
-    ASSERT_NE(cameraDevice3_8, nullptr);
-    bool supported = false;
-    ret = cameraDevice3_8->isStreamCombinationSupported_3_8(
-            config3_8, [&supported](Status s, bool combStatus) {
-                ASSERT_TRUE((Status::OK == s) || (Status::METHOD_NOT_SUPPORTED == s));
-                if (Status::OK == s) {
-                    supported = combStatus;
-                }
-            });
-    ASSERT_TRUE(ret.isOk());
-    ASSERT_EQ(supported, true);
-
-    if (*session3_8 != nullptr) {
-        ret = (*session3_8)
-                      ->configureStreams_3_8(
-                              config3_8,
-                              [&](Status s, device::V3_6::HalStreamConfiguration halConfig) {
-                                  ASSERT_EQ(Status::OK, s);
-                                  *halStreamConfig = halConfig;
-                                  if (*useHalBufManager) {
-                                      hidl_vec<V3_4::Stream> streams(1);
-                                      hidl_vec<V3_2::HalStream> halStreams(1);
-                                      streams[0] = streams3_8[0].v3_7.v3_4;
-                                      halStreams[0] = halConfig.streams[0].v3_4.v3_3.v3_2;
-                                      cb->setCurrentStreamConfig(streams, halStreams);
-                                  }
-                              });
-    }
-    *previewStream = streams3_8[0].v3_7.v3_4.v3_2;
-    ASSERT_TRUE(ret.isOk());
-}
-
 // Configure multiple preview streams using different physical ids.
 void CameraHidlTest::configurePreviewStreams3_4(const std::string &name, int32_t deviceVersion,
         sp<ICameraProvider> provider,
@@ -8041,9 +7130,8 @@
     sp<device::V3_3::ICameraDeviceSession> session3_3;
     sp<device::V3_6::ICameraDeviceSession> session3_6;
     sp<device::V3_7::ICameraDeviceSession> session3_7;
-    sp<device::V3_8::ICameraDeviceSession> session3_8;
-    castSession(session, deviceVersion, &session3_3, session3_4, session3_5,
-            &session3_6, &session3_7, &session3_8);
+    castSession(session, deviceVersion, &session3_3, session3_4, session3_5, &session3_6,
+                &session3_7);
     ASSERT_NE(nullptr, (*session3_4).get());
 
     *useHalBufManager = false;
@@ -8088,8 +7176,7 @@
     if (allowUnsupport) {
         sp<device::V3_5::ICameraDevice> cameraDevice3_5;
         sp<device::V3_7::ICameraDevice> cameraDevice3_7;
-        sp<device::V3_8::ICameraDevice> cameraDevice3_8;
-        castDevice(device3_x, deviceVersion, &cameraDevice3_5, &cameraDevice3_7, &cameraDevice3_8);
+        castDevice(device3_x, deviceVersion, &cameraDevice3_5, &cameraDevice3_7);
 
         bool supported = false;
         ret = cameraDevice3_5->isStreamCombinationSupported(config3_4,
@@ -8282,95 +7369,6 @@
     return false;
 }
 
-void CameraHidlTest::get10BitDynamicRangeProfiles(const camera_metadata_t* staticMeta,
-        std::vector<CameraMetadataEnumAndroidRequestAvailableDynamicRangeProfilesMap> *profiles) {
-    ASSERT_NE(nullptr, staticMeta);
-    ASSERT_NE(nullptr, profiles);
-    camera_metadata_ro_entry entry;
-    std::unordered_set<int64_t> entries;
-    int rc = find_camera_metadata_ro_entry(staticMeta,
-            ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP, &entry);
-    ASSERT_EQ(rc, 0);
-    ASSERT_TRUE(entry.count > 0);
-    ASSERT_EQ(entry.count % 3, 0);
-
-    for (uint32_t i = 0; i < entry.count; i += 3) {
-        ASSERT_NE(entry.data.i64[i],
-                ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_STANDARD);
-        ASSERT_EQ(entries.find(entry.data.i64[i]), entries.end());
-        entries.insert(entry.data.i64[i]);
-        profiles->emplace_back(
-                static_cast<CameraMetadataEnumAndroidRequestAvailableDynamicRangeProfilesMap>
-                (entry.data.i64[i]));
-    }
-
-    if (!entries.empty()) {
-        ASSERT_NE(entries.find(ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_HLG10),
-                entries.end());
-    }
-}
-
-bool CameraHidlTest::is10BitDynamicRangeCapable(const camera_metadata_t* staticMeta) {
-    camera_metadata_ro_entry scalarEntry;
-    int rc = find_camera_metadata_ro_entry(staticMeta, ANDROID_REQUEST_AVAILABLE_CAPABILITIES,
-                                           &scalarEntry);
-    if (rc == 0) {
-        for (uint32_t i = 0; i < scalarEntry.count; i++) {
-            if (scalarEntry.data.u8[i] ==
-                ANDROID_REQUEST_AVAILABLE_CAPABILITIES_DYNAMIC_RANGE_TEN_BIT) {
-                return true;
-            }
-        }
-    }
-    return false;
-}
-
-void CameraHidlTest::verify10BitMetadata(HandleImporter& importer,
-        const InFlightRequest& request,
-        CameraMetadataEnumAndroidRequestAvailableDynamicRangeProfilesMap profile) {
-    for (const auto& b : request.resultOutputBuffers) {
-        bool smpte2086Present = importer.isSmpte2086Present(b.buffer.buffer.getNativeHandle());
-        bool smpte2094_10Present = importer.isSmpte2094_10Present(
-                b.buffer.buffer.getNativeHandle());
-        bool smpte2094_40Present = importer.isSmpte2094_40Present(
-                b.buffer.buffer.getNativeHandle());
-
-        switch (static_cast<int64_t>(profile)) {
-            case ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_HLG10:
-                ASSERT_FALSE(smpte2086Present);
-                ASSERT_FALSE(smpte2094_10Present);
-                ASSERT_FALSE(smpte2094_40Present);
-                break;
-            case ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_HDR10:
-                ASSERT_TRUE(smpte2086Present);
-                ASSERT_FALSE(smpte2094_10Present);
-                ASSERT_FALSE(smpte2094_40Present);
-                break;
-            case ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_HDR10_PLUS:
-                ASSERT_FALSE(smpte2086Present);
-                ASSERT_FALSE(smpte2094_10Present);
-                ASSERT_TRUE(smpte2094_40Present);
-                break;
-            case ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_10B_HDR_REF:
-            case ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_10B_HDR_REF_PO:
-            case ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_10B_HDR_OEM:
-            case ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_10B_HDR_OEM_PO:
-            case ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_8B_HDR_REF:
-            case ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_8B_HDR_REF_PO:
-            case ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_8B_HDR_OEM:
-            case ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_DOLBY_VISION_8B_HDR_OEM_PO:
-                ASSERT_FALSE(smpte2086Present);
-                ASSERT_TRUE(smpte2094_10Present);
-                ASSERT_FALSE(smpte2094_40Present);
-                break;
-            default:
-                ALOGE("%s: Unexpected 10-bit dynamic range profile: %" PRId64,
-                        __FUNCTION__, profile);
-                ADD_FAILURE();
-        }
-    }
-}
-
 bool CameraHidlTest::isDepthOnly(const camera_metadata_t* staticMeta) {
     camera_metadata_ro_entry scalarEntry;
     camera_metadata_ro_entry depthEntry;
@@ -8534,9 +7532,8 @@
     sp<device::V3_5::ICameraDeviceSession> session3_5;
     sp<device::V3_6::ICameraDeviceSession> session3_6;
     sp<device::V3_7::ICameraDeviceSession> session3_7;
-    sp<device::V3_8::ICameraDeviceSession> session3_8;
-    castSession(*session, deviceVersion, &session3_3, &session3_4, &session3_5,
-            &session3_6, &session3_7, &session3_8);
+    castSession(*session, deviceVersion, &session3_3, &session3_4, &session3_5, &session3_6,
+                &session3_7);
 
     *useHalBufManager = false;
     status = find_camera_metadata_ro_entry(staticMeta,
@@ -8667,19 +7664,11 @@
 void CameraHidlTest::castDevice(const sp<device::V3_2::ICameraDevice>& device,
                                 int32_t deviceVersion,
                                 sp<device::V3_5::ICameraDevice>* device3_5 /*out*/,
-                                sp<device::V3_7::ICameraDevice>* device3_7 /*out*/,
-                                sp<device::V3_8::ICameraDevice>* device3_8 /*out*/) {
+                                sp<device::V3_7::ICameraDevice>* device3_7 /*out*/) {
     ASSERT_NE(nullptr, device3_5);
     ASSERT_NE(nullptr, device3_7);
-    ASSERT_NE(nullptr, device3_8);
 
     switch (deviceVersion) {
-        case CAMERA_DEVICE_API_VERSION_3_8: {
-            auto castResult = device::V3_8::ICameraDevice::castFrom(device);
-            ASSERT_TRUE(castResult.isOk());
-            *device3_8 = castResult;
-        }
-            [[fallthrough]];
         case CAMERA_DEVICE_API_VERSION_3_7: {
             auto castResult = device::V3_7::ICameraDevice::castFrom(device);
             ASSERT_TRUE(castResult.isOk());
@@ -8723,27 +7712,19 @@
 }
 
 //Cast camera device session to corresponding version
-void CameraHidlTest::castSession(const sp<ICameraDeviceSession> &session, int32_t deviceVersion,
-        sp<device::V3_3::ICameraDeviceSession> *session3_3 /*out*/,
-        sp<device::V3_4::ICameraDeviceSession> *session3_4 /*out*/,
-        sp<device::V3_5::ICameraDeviceSession> *session3_5 /*out*/,
-        sp<device::V3_6::ICameraDeviceSession> *session3_6 /*out*/,
-        sp<device::V3_7::ICameraDeviceSession> *session3_7 /*out*/,
-        sp<device::V3_8::ICameraDeviceSession> *session3_8 /*out*/) {
+void CameraHidlTest::castSession(const sp<ICameraDeviceSession>& session, int32_t deviceVersion,
+                                 sp<device::V3_3::ICameraDeviceSession>* session3_3 /*out*/,
+                                 sp<device::V3_4::ICameraDeviceSession>* session3_4 /*out*/,
+                                 sp<device::V3_5::ICameraDeviceSession>* session3_5 /*out*/,
+                                 sp<device::V3_6::ICameraDeviceSession>* session3_6 /*out*/,
+                                 sp<device::V3_7::ICameraDeviceSession>* session3_7 /*out*/) {
     ASSERT_NE(nullptr, session3_3);
     ASSERT_NE(nullptr, session3_4);
     ASSERT_NE(nullptr, session3_5);
     ASSERT_NE(nullptr, session3_6);
     ASSERT_NE(nullptr, session3_7);
-    ASSERT_NE(nullptr, session3_8);
 
     switch (deviceVersion) {
-        case CAMERA_DEVICE_API_VERSION_3_8: {
-            auto castResult = device::V3_8::ICameraDeviceSession::castFrom(session);
-            ASSERT_TRUE(castResult.isOk());
-            *session3_8 = castResult;
-        }
-        [[fallthrough]];
         case CAMERA_DEVICE_API_VERSION_3_7: {
             auto castResult = device::V3_7::ICameraDeviceSession::castFrom(session);
             ASSERT_TRUE(castResult.isOk());
@@ -9661,9 +8642,8 @@
     sp<device::V3_5::ICameraDeviceSession> session3_5;
     sp<device::V3_6::ICameraDeviceSession> session3_6;
     sp<device::V3_7::ICameraDeviceSession> session3_7;
-    sp<device::V3_8::ICameraDeviceSession> session3_8;
-    castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5,
-            &session3_6, &session3_7, &session3_8);
+    castSession(session, deviceVersion, &session3_3, &session3_4, &session3_5, &session3_6,
+                &session3_7);
     ASSERT_NE(nullptr, session3_5.get());
 
     hidl_vec<int32_t> streamIds(1);
@@ -9905,7 +8885,7 @@
     size_t CONFIG_ENTRY_TYPE_OFFSET = 3;
     size_t CONFIG_ENTRY_BITFIELD_OFFSET = 4;
     uint32_t maxPublicUsecase =
-            ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS_PUBLIC_END_3_8;
+            ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS_PUBLIC_END;
     uint32_t vendorUsecaseStart =
             ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS_VENDOR_START;
     uint32_t usecaseMask = (1 << vendorUsecaseStart) - 1;
diff --git a/camera/provider/aidl/vts/VtsAidlHalCameraProvider_TargetTest.cpp b/camera/provider/aidl/vts/VtsAidlHalCameraProvider_TargetTest.cpp
index 462698c..70ab7a0 100644
--- a/camera/provider/aidl/vts/VtsAidlHalCameraProvider_TargetTest.cpp
+++ b/camera/provider/aidl/vts/VtsAidlHalCameraProvider_TargetTest.cpp
@@ -39,7 +39,7 @@
 using ::aidl::android::hardware::camera::metadata::RequestAvailableDynamicRangeProfilesMap;
 using ::aidl::android::hardware::camera::metadata::SensorPixelMode;
 using ::aidl::android::hardware::camera::provider::CameraIdAndStreamCombination;
-using ::aidl::android::hardware::camera::provider::ICameraProviderCallbackDefault;
+using ::aidl::android::hardware::camera::provider::BnCameraProviderCallback;
 
 using ::ndk::ScopedAStatus;
 
@@ -86,7 +86,7 @@
 
 // Test if ICameraProvider::setCallback returns Status::OK
 TEST_P(CameraAidlTest, setCallback) {
-    struct ProviderCb : public ICameraProviderCallbackDefault {
+    struct ProviderCb : public BnCameraProviderCallback {
         ScopedAStatus cameraDeviceStatusChange(const std::string& cameraDeviceName,
                                                CameraDeviceStatus newStatus) override {
             ALOGI("camera device status callback name %s, status %d", cameraDeviceName.c_str(),
@@ -109,11 +109,11 @@
         }
     };
 
-    std::shared_ptr<ProviderCb> cb = ProviderCb::make<ProviderCb>();
+    std::shared_ptr<ProviderCb> cb = ndk::SharedRefBase::make<ProviderCb>();
     ScopedAStatus ret = mProvider->setCallback(cb);
     ASSERT_TRUE(ret.isOk());
     ret = mProvider->setCallback(nullptr);
-    ASSERT_TRUE(ret.isOk());
+    ASSERT_EQ(static_cast<int32_t>(Status::ILLEGAL_ARGUMENT), ret.getServiceSpecificError());
 }
 
 // Test if ICameraProvider::getCameraDeviceInterface returns Status::OK and non-null device
@@ -399,9 +399,6 @@
             }
         }
     }
-
-    ret = mProvider->setCallback(nullptr);
-    ASSERT_TRUE(ret.isOk());
 }
 
 // Check dump functionality.
@@ -1742,6 +1739,10 @@
 
         std::list<PixelFormat> pixelFormats = {PixelFormat::YCBCR_420_888, PixelFormat::RAW16};
         for (PixelFormat format : pixelFormats) {
+            previewStream.usage =
+                static_cast<aidl::android::hardware::graphics::common::BufferUsage>(
+                        GRALLOC1_CONSUMER_USAGE_CPU_READ);
+            previewStream.dataSpace = Dataspace::UNKNOWN;
             configureStreams(name, mProvider, format, &mSession, &previewStream, &halStreams,
                              &supportsPartialResults, &partialResultCount, &useHalBufManager, &cb,
                              0, /*maxResolution*/ true);
@@ -1846,7 +1847,6 @@
 TEST_P(CameraAidlTest, process10BitDynamicRangeRequest) {
     std::vector<std::string> cameraDeviceNames = getCameraDeviceNames(mProvider);
     int64_t bufferId = 1;
-    int32_t frameNumber = 1;
     CameraMetadata settings;
 
     for (const auto& name : cameraDeviceNames) {
@@ -1869,7 +1869,7 @@
         CameraMetadata req;
         android::hardware::camera::common::V1_0::helper::CameraMetadata defaultSettings;
         ndk::ScopedAStatus ret =
-                mSession->constructDefaultRequestSettings(RequestTemplate::STILL_CAPTURE, &req);
+                mSession->constructDefaultRequestSettings(RequestTemplate::PREVIEW, &req);
         ASSERT_TRUE(ret.isOk());
 
         const camera_metadata_t* metadata =
@@ -1899,6 +1899,10 @@
         Stream previewStream;
         std::shared_ptr<DeviceCb> cb;
         for (const auto& profile : profileList) {
+            previewStream.usage =
+                static_cast<aidl::android::hardware::graphics::common::BufferUsage>(
+                        GRALLOC1_CONSUMER_USAGE_HWCOMPOSER);
+            previewStream.dataSpace = getDataspace(PixelFormat::IMPLEMENTATION_DEFINED);
             configureStreams(name, mProvider, PixelFormat::IMPLEMENTATION_DEFINED, &mSession,
                              &previewStream, &halStreams, &supportsPartialResults,
                              &partialResultCount, &useHalBufManager, &cb, 0,
@@ -1919,63 +1923,75 @@
                 // Don't use the queue onwards.
             }
 
-            std::vector<buffer_handle_t> graphicBuffers;
-            graphicBuffers.reserve(halStreams.size());
+            mInflightMap.clear();
+            // Stream as long as needed to fill the Hal inflight queue
+            std::vector<CaptureRequest> requests(halStreams[0].maxBuffers);
 
-            std::shared_ptr<InFlightRequest> inflightReq = std::make_shared<InFlightRequest>(
-                    static_cast<ssize_t>(halStreams.size()), false, supportsPartialResults,
-                    partialResultCount, std::unordered_set<std::string>(), resultQueue);
+            for (int32_t frameNumber = 0; frameNumber < requests.size(); frameNumber++) {
+                std::shared_ptr<InFlightRequest> inflightReq = std::make_shared<InFlightRequest>(
+                        static_cast<ssize_t>(halStreams.size()), false, supportsPartialResults,
+                        partialResultCount, std::unordered_set<std::string>(), resultQueue);
 
-            std::vector<CaptureRequest> requests(1);
-            CaptureRequest& request = requests[0];
-            std::vector<StreamBuffer>& outputBuffers = request.outputBuffers;
-            outputBuffers.resize(halStreams.size());
+                CaptureRequest& request = requests[frameNumber];
+                std::vector<StreamBuffer>& outputBuffers = request.outputBuffers;
+                outputBuffers.resize(halStreams.size());
 
-            size_t k = 0;
-            for (const auto& halStream : halStreams) {
-                buffer_handle_t buffer_handle;
-                if (useHalBufManager) {
-                    outputBuffers[k] = {halStream.id,   0,
-                                        NativeHandle(), BufferStatus::OK,
-                                        NativeHandle(), NativeHandle()};
-                } else {
-                    allocateGraphicBuffer(previewStream.width, previewStream.height,
-                                          android_convertGralloc1To0Usage(
-                                                  static_cast<uint64_t>(halStream.producerUsage),
-                                                  static_cast<uint64_t>(halStream.consumerUsage)),
-                                          halStream.overrideFormat, &buffer_handle);
+                size_t k = 0;
+                inflightReq->mOutstandingBufferIds.resize(halStreams.size());
+                std::vector<buffer_handle_t> graphicBuffers;
+                graphicBuffers.reserve(halStreams.size());
 
-                    graphicBuffers.push_back(buffer_handle);
-                    outputBuffers[k] = {
-                            halStream.id,     bufferId,       android::makeToAidl(buffer_handle),
-                            BufferStatus::OK, NativeHandle(), NativeHandle()};
-                    bufferId++;
+                for (const auto& halStream : halStreams) {
+                    buffer_handle_t buffer_handle;
+                    if (useHalBufManager) {
+                        outputBuffers[k] = {halStream.id,   0,
+                                            NativeHandle(), BufferStatus::OK,
+                                            NativeHandle(), NativeHandle()};
+                    } else {
+                        auto usage = android_convertGralloc1To0Usage(
+                                static_cast<uint64_t>(halStream.producerUsage),
+                                static_cast<uint64_t>(halStream.consumerUsage));
+                        allocateGraphicBuffer(previewStream.width, previewStream.height, usage,
+                                              halStream.overrideFormat, &buffer_handle);
+
+                        inflightReq->mOutstandingBufferIds[halStream.id][bufferId] = buffer_handle;
+                        graphicBuffers.push_back(buffer_handle);
+                        outputBuffers[k] = {halStream.id, bufferId,
+                            android::makeToAidl(buffer_handle), BufferStatus::OK, NativeHandle(),
+                            NativeHandle()};
+                        bufferId++;
+                    }
+                    k++;
                 }
-                k++;
-            }
 
-            request.inputBuffer = {
-                    -1, 0, NativeHandle(), BufferStatus::ERROR, NativeHandle(), NativeHandle()};
-            request.frameNumber = frameNumber;
-            request.fmqSettingsSize = 0;
-            request.settings = settings;
-            request.inputWidth = 0;
-            request.inputHeight = 0;
+                request.inputBuffer = {
+                        -1, 0, NativeHandle(), BufferStatus::ERROR, NativeHandle(), NativeHandle()};
+                request.frameNumber = frameNumber;
+                request.fmqSettingsSize = 0;
+                request.settings = settings;
+                request.inputWidth = 0;
+                request.inputHeight = 0;
 
-            {
-                std::unique_lock<std::mutex> l(mLock);
-                mInflightMap.clear();
-                mInflightMap[frameNumber] = inflightReq;
+                {
+                    std::unique_lock<std::mutex> l(mLock);
+                    mInflightMap[frameNumber] = inflightReq;
+                }
+
             }
 
             int32_t numRequestProcessed = 0;
             std::vector<BufferCache> cachesToRemove;
             ndk::ScopedAStatus returnStatus =
-                    mSession->processCaptureRequest(requests, cachesToRemove, &numRequestProcessed);
+                mSession->processCaptureRequest(requests, cachesToRemove, &numRequestProcessed);
             ASSERT_TRUE(returnStatus.isOk());
-            ASSERT_EQ(numRequestProcessed, 1u);
+            ASSERT_EQ(numRequestProcessed, requests.size());
 
-            {
+            returnStatus = mSession->repeatingRequestEnd(requests.size() - 1,
+                    std::vector<int32_t> {halStreams[0].id});
+            ASSERT_TRUE(returnStatus.isOk());
+
+            for (int32_t frameNumber = 0; frameNumber < requests.size(); frameNumber++) {
+                const auto& inflightReq = mInflightMap[frameNumber];
                 std::unique_lock<std::mutex> l(mLock);
                 while (!inflightReq->errorCodeValid &&
                        ((0 < inflightReq->numBuffersLeft) || (!inflightReq->haveResultMetadata))) {
@@ -1988,6 +2004,7 @@
                 ASSERT_NE(inflightReq->resultOutputBuffers.size(), 0u);
                 verify10BitMetadata(mHandleImporter, *inflightReq, profile);
             }
+
             if (useHalBufManager) {
                 std::vector<int32_t> streamIds(halStreams.size());
                 for (size_t i = 0; i < streamIds.size(); i++) {
diff --git a/camera/provider/aidl/vts/camera_aidl_test.cpp b/camera/provider/aidl/vts/camera_aidl_test.cpp
index fd83e37..20f32bf 100644
--- a/camera/provider/aidl/vts/camera_aidl_test.cpp
+++ b/camera/provider/aidl/vts/camera_aidl_test.cpp
@@ -55,26 +55,6 @@
 using ::ndk::SpAIBinder;
 
 namespace {
-bool matchDeviceName(const std::string& deviceName, const std::string& providerType,
-                     std::string* deviceVersion, std::string* cameraId) {
-    // expected format: device@<major>.<minor>/<type>/<id>
-    std::stringstream pattern;
-    pattern << "device@[0-9]+\\.[0-9]+/" << providerType << "/(.+)";
-    std::regex e(pattern.str());
-
-    std::smatch sm;
-    if (std::regex_match(deviceName, sm, e)) {
-        if (deviceVersion != nullptr) {
-            *deviceVersion = sm[1];
-        }
-        if (cameraId != nullptr) {
-            *cameraId = sm[2];
-        }
-        return true;
-    }
-    return false;
-}
-
 bool parseProviderName(const std::string& serviceDescriptor, std::string* type /*out*/,
                        uint32_t* id /*out*/) {
     if (!type || !id) {
@@ -498,13 +478,11 @@
 
 bool CameraAidlTest::matchDeviceName(const std::string& deviceName, const std::string& providerType,
                                      std::string* deviceVersion, std::string* cameraId) {
-    // "device@<version>/legacy/<id>"
-    std::string pattern;
-    pattern.append("device@([0-9]+\\.[0-9]+)/");
-    pattern.append(providerType);
-    pattern.append("/(.+)");
+    // expected format: device@<major>.<minor>/<type>/<id>
+    std::stringstream pattern;
+    pattern << "device@([0-9]+\\.[0-9]+)/" << providerType << "/(.+)";
+    std::regex e(pattern.str());
 
-    std::regex e(pattern);
     std::smatch sm;
     if (std::regex_match(deviceName, sm, e)) {
         if (deviceVersion != nullptr) {
@@ -1160,7 +1138,7 @@
     }
 
     std::string version, cameraId;
-    ASSERT_TRUE(::matchDeviceName(cameraName, mProviderType, &version, &cameraId));
+    ASSERT_TRUE(matchDeviceName(cameraName, mProviderType, &version, &cameraId));
     std::unordered_set<std::string> physicalIds;
     rc = getPhysicalCameraIds(metadata, &physicalIds);
     ASSERT_TRUE(isUltraHighResCamera || Status::OK == rc);
@@ -1192,7 +1170,7 @@
         SystemCameraKind physSystemCameraKind = SystemCameraKind::PUBLIC;
         for (auto& deviceName : deviceNames) {
             std::string publicVersion, publicId;
-            ASSERT_TRUE(::matchDeviceName(deviceName, mProviderType, &publicVersion, &publicId));
+            ASSERT_TRUE(matchDeviceName(deviceName, mProviderType, &publicVersion, &publicId));
             if (physicalId == publicId) {
                 isPublicId = true;
                 fullPublicId = deviceName;
@@ -2661,8 +2639,20 @@
 
     outputStreams.clear();
     Size maxSize;
-    auto rc = getMaxOutputSizeForFormat(staticMeta, format, &maxSize, maxResolution);
-    ASSERT_EQ(Status::OK, rc);
+    if (maxResolution) {
+        auto rc = getMaxOutputSizeForFormat(staticMeta, format, &maxSize, maxResolution);
+        ASSERT_EQ(Status::OK, rc);
+    } else {
+        AvailableStream previewThreshold = {kMaxPreviewWidth, kMaxPreviewHeight,
+            static_cast<int32_t>(format)};
+        auto rc = getAvailableOutputStreams(staticMeta, outputStreams, &previewThreshold);
+
+        ASSERT_EQ(Status::OK, rc);
+        ASSERT_FALSE(outputStreams.empty());
+        maxSize.width = outputStreams[0].width;
+        maxSize.height = outputStreams[0].height;
+    }
+
 
     std::vector<Stream> streams(1);
     streams[0] = {0,
@@ -2670,9 +2660,8 @@
                   maxSize.width,
                   maxSize.height,
                   format,
-                  static_cast<::aidl::android::hardware::graphics::common::BufferUsage>(
-                          GRALLOC1_CONSUMER_USAGE_CPU_READ),
-                  Dataspace::UNKNOWN,
+                  previewStream->usage,
+                  previewStream->dataSpace,
                   StreamRotation::ROTATION_0,
                   "",
                   0,
@@ -2758,7 +2747,8 @@
         HandleImporter& importer, const InFlightRequest& request,
         aidl::android::hardware::camera::metadata::RequestAvailableDynamicRangeProfilesMap
                 profile) {
-    for (const auto& b : request.resultOutputBuffers) {
+    for (auto b : request.resultOutputBuffers) {
+        importer.importBuffer(b.buffer.buffer);
         bool smpte2086Present = importer.isSmpte2086Present(b.buffer.buffer);
         bool smpte2094_10Present = importer.isSmpte2094_10Present(b.buffer.buffer);
         bool smpte2094_40Present = importer.isSmpte2094_40Present(b.buffer.buffer);
@@ -2775,7 +2765,6 @@
                 ASSERT_FALSE(smpte2094_40Present);
                 break;
             case ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_HDR10_PLUS:
-                ASSERT_FALSE(smpte2086Present);
                 ASSERT_FALSE(smpte2094_10Present);
                 ASSERT_TRUE(smpte2094_40Present);
                 break;
@@ -2796,6 +2785,7 @@
                       profile);
                 ADD_FAILURE();
         }
+        importer.freeBuffer(b.buffer.buffer);
     }
 }
 
diff --git a/camera/provider/aidl/vts/camera_aidl_test.h b/camera/provider/aidl/vts/camera_aidl_test.h
index ac4b2c9..d828cee 100644
--- a/camera/provider/aidl/vts/camera_aidl_test.h
+++ b/camera/provider/aidl/vts/camera_aidl_test.h
@@ -399,6 +399,10 @@
         // Result metadata
         ::android::hardware::camera::common::V1_0::helper::CameraMetadata collectedResult;
 
+        // Inflight buffers
+        using OutstandingBuffers = std::unordered_map<uint64_t, buffer_handle_t>;
+        std::vector<OutstandingBuffers> mOutstandingBufferIds;
+
         // A copy-able StreamBuffer using buffer_handle_t instead of AIDLs NativeHandle
         struct NativeStreamBuffer {
             int32_t streamId;
diff --git a/camera/provider/aidl/vts/device_cb.cpp b/camera/provider/aidl/vts/device_cb.cpp
index e5f2f1e..4698b4a 100644
--- a/camera/provider/aidl/vts/device_cb.cpp
+++ b/camera/provider/aidl/vts/device_cb.cpp
@@ -155,7 +155,7 @@
                     BufferStatus::OK, NativeHandle(), NativeHandle(),
             };
 
-            mOutstandingBufferIds[idx][mNextBufferId++] = ::android::dupToAidl(handle);
+            mOutstandingBufferIds[idx][mNextBufferId++] = handle;
         }
         atLeastOneStreamOk = true;
         bufRets[i].streamId = stream.id;
@@ -427,9 +427,13 @@
         }
 
         CameraAidlTest::InFlightRequest::StreamBufferAndTimestamp streamBufferAndTimestamp;
+        auto outstandingBuffers = mUseHalBufManager ? mOutstandingBufferIds :
+            request->mOutstandingBufferIds;
+        auto outputBuffer = outstandingBuffers.empty() ? ::android::makeFromAidl(buffer.buffer) :
+            outstandingBuffers[buffer.streamId][buffer.bufferId];
         streamBufferAndTimestamp.buffer = {buffer.streamId,
                                            buffer.bufferId,
-                                           ::android::makeFromAidl(buffer.buffer),
+                                           outputBuffer,
                                            buffer.status,
                                            ::android::makeFromAidl(buffer.acquireFence),
                                            ::android::makeFromAidl(buffer.releaseFence)};
diff --git a/camera/provider/aidl/vts/device_cb.h b/camera/provider/aidl/vts/device_cb.h
index 82ca10d..3ae7d10 100644
--- a/camera/provider/aidl/vts/device_cb.h
+++ b/camera/provider/aidl/vts/device_cb.h
@@ -73,7 +73,7 @@
     std::vector<Stream> mStreams;
     std::vector<HalStream> mHalStreams;
     int64_t mNextBufferId = 1;
-    using OutstandingBuffers = std::unordered_map<uint64_t, NativeHandle>;
+    using OutstandingBuffers = std::unordered_map<uint64_t, buffer_handle_t>;
     // size == mStreams.size(). Tracking each streams outstanding buffers
     std::vector<OutstandingBuffers> mOutstandingBufferIds;
     std::condition_variable mFlushedCondition;
diff --git a/drm/aidl/vts/drm_hal_common.cpp b/drm/aidl/vts/drm_hal_common.cpp
index de7dc28..7de8167 100644
--- a/drm/aidl/vts/drm_hal_common.cpp
+++ b/drm/aidl/vts/drm_hal_common.cpp
@@ -73,6 +73,7 @@
 }
 
 const char* kDrmIface = "android.hardware.drm.IDrmFactory";
+const int MAX_OPEN_SESSION_ATTEMPTS = 3;
 
 std::string HalFullName(const std::string& iface, const std::string& basename) {
     return iface + '/' + basename;
@@ -328,9 +329,19 @@
  */
 SessionId DrmHalTest::openSession() {
     SessionId sessionId;
-    auto ret = drmPlugin->openSession(SecurityLevel::DEFAULT, &sessionId);
-    EXPECT_OK(ret);
-    EXPECT_NE(0u, sessionId.size());
+
+    int attmpt = 0;
+    while (attmpt++ < MAX_OPEN_SESSION_ATTEMPTS) {
+        auto ret = drmPlugin->openSession(SecurityLevel::DEFAULT, &sessionId);
+        if(DrmErr(ret) == Status::ERROR_DRM_NOT_PROVISIONED) {
+            provision();
+        } else {
+            EXPECT_OK(ret);
+            EXPECT_NE(0u, sessionId.size());
+            break;
+        }
+    }
+
     return sessionId;
 }
 
diff --git a/gnss/aidl/default/Gnss.cpp b/gnss/aidl/default/Gnss.cpp
index 7855b51..cf2c90d 100644
--- a/gnss/aidl/default/Gnss.cpp
+++ b/gnss/aidl/default/Gnss.cpp
@@ -19,6 +19,7 @@
 #include "Gnss.h"
 #include <inttypes.h>
 #include <log/log.h>
+#include <utils/Timers.h>
 #include "AGnss.h"
 #include "AGnssRil.h"
 #include "DeviceFileReader.h"
@@ -28,7 +29,6 @@
 #include "GnssConfiguration.h"
 #include "GnssDebug.h"
 #include "GnssGeofence.h"
-#include "GnssMeasurementInterface.h"
 #include "GnssNavigationMessageInterface.h"
 #include "GnssPsds.h"
 #include "GnssVisibilityControl.h"
@@ -95,6 +95,9 @@
     }
 
     mIsActive = true;
+    mThreadBlocker.reset();
+    // notify measurement engine to update measurement interval
+    mGnssMeasurementInterface->setLocationEnabled(true);
     this->reportGnssStatusValue(IGnssCallback::GnssStatusValue::SESSION_BEGIN);
     mThread = std::thread([this]() {
         this->reportSvStatus();
@@ -102,8 +105,12 @@
             std::this_thread::sleep_for(std::chrono::milliseconds(TTFF_MILLIS));
             mFirstFixReceived = true;
         }
-        while (mIsActive == true) {
+        do {
+            if (!mIsActive) {
+                break;
+            }
             this->reportSvStatus();
+            this->reportNmea();
 
             auto currentLocation = getLocationFromHW();
             mGnssPowerIndication->notePowerConsumption();
@@ -113,12 +120,29 @@
                 const auto location = Utils::getMockLocation();
                 this->reportLocation(location);
             }
-            std::this_thread::sleep_for(std::chrono::milliseconds(mMinIntervalMs));
-        }
+        } while (mIsActive && mThreadBlocker.wait_for(std::chrono::milliseconds(mMinIntervalMs)));
     });
     return ScopedAStatus::ok();
 }
 
+ScopedAStatus Gnss::stop() {
+    ALOGD("stop");
+    mIsActive = false;
+    mGnssMeasurementInterface->setLocationEnabled(false);
+    this->reportGnssStatusValue(IGnssCallback::GnssStatusValue::SESSION_END);
+    mThreadBlocker.notify();
+    if (mThread.joinable()) {
+        mThread.join();
+    }
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus Gnss::close() {
+    ALOGD("close");
+    sGnssCallback = nullptr;
+    return ScopedAStatus::ok();
+}
+
 void Gnss::reportLocation(const GnssLocation& location) const {
     std::unique_lock<std::mutex> lock(mMutex);
     if (sGnssCallback == nullptr) {
@@ -153,7 +177,6 @@
 
 std::vector<GnssSvInfo> Gnss::filterBlocklistedSatellites(
         std::vector<GnssSvInfo> gnssSvInfoList) const {
-    ALOGD("filterBlocklistedSatellites");
     for (uint32_t i = 0; i < gnssSvInfoList.size(); i++) {
         if (mGnssConfiguration->isBlocklisted(gnssSvInfoList[i])) {
             gnssSvInfoList[i].svFlag &= ~(uint32_t)IGnssCallback::GnssSvFlags::USED_IN_FIX;
@@ -174,14 +197,19 @@
     }
 }
 
-ScopedAStatus Gnss::stop() {
-    ALOGD("stop");
-    mIsActive = false;
-    this->reportGnssStatusValue(IGnssCallback::GnssStatusValue::SESSION_END);
-    if (mThread.joinable()) {
-        mThread.join();
+void Gnss::reportNmea() const {
+    if (mIsNmeaActive) {
+        std::unique_lock<std::mutex> lock(mMutex);
+        if (sGnssCallback == nullptr) {
+            ALOGE("%s: sGnssCallback is null.", __func__);
+            return;
+        }
+        nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
+        auto status = sGnssCallback->gnssNmeaCb(now, "$TEST,0,1,2,3,4,5");
+        if (!status.isOk()) {
+            ALOGE("%s: Unable to invoke callback", __func__);
+        }
     }
-    return ScopedAStatus::ok();
 }
 
 ScopedAStatus Gnss::startSvStatus() {
@@ -197,16 +225,12 @@
 }
 ScopedAStatus Gnss::startNmea() {
     ALOGD("startNmea");
+    mIsNmeaActive = true;
     return ScopedAStatus::ok();
 }
 ScopedAStatus Gnss::stopNmea() {
     ALOGD("stopNmea");
-    return ScopedAStatus::ok();
-}
-
-ScopedAStatus Gnss::close() {
-    ALOGD("close");
-    sGnssCallback = nullptr;
+    mIsNmeaActive = false;
     return ScopedAStatus::ok();
 }
 
@@ -249,7 +273,8 @@
 ScopedAStatus Gnss::setPositionMode(const PositionModeOptions& options) {
     ALOGD("setPositionMode. minIntervalMs:%d, lowPowerMode:%d", options.minIntervalMs,
           (int)options.lowPowerMode);
-    mMinIntervalMs = options.minIntervalMs;
+    mMinIntervalMs = std::max(1000, options.minIntervalMs);
+    mGnssMeasurementInterface->setLocationInterval(mMinIntervalMs);
     return ScopedAStatus::ok();
 }
 
@@ -283,8 +308,10 @@
 ScopedAStatus Gnss::getExtensionGnssMeasurement(
         std::shared_ptr<IGnssMeasurementInterface>* iGnssMeasurement) {
     ALOGD("getExtensionGnssMeasurement");
-
-    *iGnssMeasurement = SharedRefBase::make<GnssMeasurementInterface>();
+    if (mGnssMeasurementInterface == nullptr) {
+        mGnssMeasurementInterface = SharedRefBase::make<GnssMeasurementInterface>();
+    }
+    *iGnssMeasurement = mGnssMeasurementInterface;
     return ScopedAStatus::ok();
 }
 
diff --git a/gnss/aidl/default/Gnss.h b/gnss/aidl/default/Gnss.h
index 1489b4b..df10fc8 100644
--- a/gnss/aidl/default/Gnss.h
+++ b/gnss/aidl/default/Gnss.h
@@ -32,7 +32,9 @@
 #include <mutex>
 #include <thread>
 #include "GnssConfiguration.h"
+#include "GnssMeasurementInterface.h"
 #include "GnssPowerIndication.h"
+#include "Utils.h"
 
 namespace aidl::android::hardware::gnss {
 
@@ -84,6 +86,7 @@
 
     std::shared_ptr<GnssConfiguration> mGnssConfiguration;
     std::shared_ptr<GnssPowerIndication> mGnssPowerIndication;
+    std::shared_ptr<GnssMeasurementInterface> mGnssMeasurementInterface;
 
   private:
     void reportLocation(const GnssLocation&) const;
@@ -93,14 +96,17 @@
             std::vector<IGnssCallback::GnssSvInfo> gnssSvInfoList) const;
     void reportGnssStatusValue(const IGnssCallback::GnssStatusValue gnssStatusValue) const;
     std::unique_ptr<GnssLocation> getLocationFromHW();
+    void reportNmea() const;
 
     static std::shared_ptr<IGnssCallback> sGnssCallback;
 
     std::atomic<long> mMinIntervalMs;
     std::atomic<bool> mIsActive;
     std::atomic<bool> mIsSvStatusActive;
+    std::atomic<bool> mIsNmeaActive;
     std::atomic<bool> mFirstFixReceived;
     std::thread mThread;
+    ::android::hardware::gnss::common::ThreadBlocker mThreadBlocker;
 
     mutable std::mutex mMutex;
 };
diff --git a/gnss/aidl/default/GnssMeasurementInterface.cpp b/gnss/aidl/default/GnssMeasurementInterface.cpp
index 2c7241b..606de07 100644
--- a/gnss/aidl/default/GnssMeasurementInterface.cpp
+++ b/gnss/aidl/default/GnssMeasurementInterface.cpp
@@ -33,10 +33,11 @@
 
 std::shared_ptr<IGnssMeasurementCallback> GnssMeasurementInterface::sCallback = nullptr;
 
-GnssMeasurementInterface::GnssMeasurementInterface() : mMinIntervalMillis(1000) {}
+GnssMeasurementInterface::GnssMeasurementInterface()
+    : mIntervalMs(1000), mLocationIntervalMs(1000), mFutures(std::vector<std::future<void>>()) {}
 
 GnssMeasurementInterface::~GnssMeasurementInterface() {
-    stop();
+    waitForStoppingThreads();
 }
 
 ndk::ScopedAStatus GnssMeasurementInterface::setCallback(
@@ -44,8 +45,10 @@
         const bool enableCorrVecOutputs) {
     ALOGD("setCallback: enableFullTracking: %d enableCorrVecOutputs: %d", (int)enableFullTracking,
           (int)enableCorrVecOutputs);
-    std::unique_lock<std::mutex> lock(mMutex);
-    sCallback = callback;
+    {
+        std::unique_lock<std::mutex> lock(mMutex);
+        sCallback = callback;
+    }
 
     if (mIsActive) {
         ALOGW("GnssMeasurement callback already set. Resetting the callback...");
@@ -60,14 +63,16 @@
         const std::shared_ptr<IGnssMeasurementCallback>& callback, const Options& options) {
     ALOGD("setCallbackWithOptions: fullTracking:%d, corrVec:%d, intervalMs:%d",
           (int)options.enableFullTracking, (int)options.enableCorrVecOutputs, options.intervalMs);
-    std::unique_lock<std::mutex> lock(mMutex);
-    sCallback = callback;
+    {
+        std::unique_lock<std::mutex> lock(mMutex);
+        sCallback = callback;
+    }
 
     if (mIsActive) {
         ALOGW("GnssMeasurement callback already set. Resetting the callback...");
         stop();
     }
-    mMinIntervalMillis = options.intervalMs;
+    mIntervalMs = std::max(options.intervalMs, 1000);
     start(options.enableCorrVecOutputs);
 
     return ndk::ScopedAStatus::ok();
@@ -75,18 +80,35 @@
 
 ndk::ScopedAStatus GnssMeasurementInterface::close() {
     ALOGD("close");
-    stop();
-    std::unique_lock<std::mutex> lock(mMutex);
-    sCallback = nullptr;
-    mMinIntervalMillis = 1000;
+    if (mIsActive) {
+        stop();
+    }
+    {
+        std::unique_lock<std::mutex> lock(mMutex);
+        sCallback = nullptr;
+    }
+    mIntervalMs = 1000;
     return ndk::ScopedAStatus::ok();
 }
 
 void GnssMeasurementInterface::start(const bool enableCorrVecOutputs) {
     ALOGD("start");
+
+    if (mIsActive) {
+        ALOGD("restarting since measurement has started");
+        stop();
+    }
+    // Wait for stopping previous thread.
+    waitForStoppingThreads();
+
     mIsActive = true;
+    mThreadBlocker.reset();
     mThread = std::thread([this, enableCorrVecOutputs]() {
-        while (mIsActive == true) {
+        int intervalMs;
+        do {
+            if (!mIsActive) {
+                break;
+            }
             std::string rawMeasurementStr = "";
             if (ReplayUtils::hasGnssDeviceFile() &&
                 ReplayUtils::isGnssRawMeasurement(
@@ -103,15 +125,19 @@
                 auto measurement = Utils::getMockMeasurement(enableCorrVecOutputs);
                 this->reportMeasurement(measurement);
             }
-            std::this_thread::sleep_for(std::chrono::milliseconds(mMinIntervalMillis));
-        }
+            intervalMs =
+                    (mLocationEnabled) ? std::min(mLocationIntervalMs, mIntervalMs) : mIntervalMs;
+        } while (mIsActive && mThreadBlocker.wait_for(std::chrono::milliseconds(intervalMs)));
     });
-    mThread.detach();
 }
 
 void GnssMeasurementInterface::stop() {
     ALOGD("stop");
     mIsActive = false;
+    mThreadBlocker.notify();
+    if (mThread.joinable()) {
+        mFutures.push_back(std::async(std::launch::async, [this] { mThread.join(); }));
+    }
 }
 
 void GnssMeasurementInterface::reportMeasurement(const GnssData& data) {
@@ -128,4 +154,21 @@
     callbackCopy->gnssMeasurementCb(data);
 }
 
+void GnssMeasurementInterface::setLocationInterval(const int intervalMs) {
+    mLocationIntervalMs = intervalMs;
+}
+
+void GnssMeasurementInterface::setLocationEnabled(const bool enabled) {
+    mLocationEnabled = enabled;
+}
+
+void GnssMeasurementInterface::waitForStoppingThreads() {
+    for (auto& future : mFutures) {
+        ALOGD("Stopping previous thread.");
+        future.wait();
+        ALOGD("Done stopping thread.");
+    }
+    mFutures.clear();
+}
+
 }  // namespace aidl::android::hardware::gnss
diff --git a/gnss/aidl/default/GnssMeasurementInterface.h b/gnss/aidl/default/GnssMeasurementInterface.h
index bf77806..bb08027 100644
--- a/gnss/aidl/default/GnssMeasurementInterface.h
+++ b/gnss/aidl/default/GnssMeasurementInterface.h
@@ -19,8 +19,10 @@
 #include <aidl/android/hardware/gnss/BnGnssMeasurementCallback.h>
 #include <aidl/android/hardware/gnss/BnGnssMeasurementInterface.h>
 #include <atomic>
+#include <future>
 #include <mutex>
 #include <thread>
+#include "Utils.h"
 
 namespace aidl::android::hardware::gnss {
 
@@ -35,15 +37,22 @@
     ndk::ScopedAStatus setCallbackWithOptions(
             const std::shared_ptr<IGnssMeasurementCallback>& callback,
             const Options& options) override;
+    void setLocationInterval(const int intervalMs);
+    void setLocationEnabled(const bool enabled);
 
   private:
     void start(const bool enableCorrVecOutputs);
     void stop();
     void reportMeasurement(const GnssData&);
+    void waitForStoppingThreads();
 
-    std::atomic<long> mMinIntervalMillis;
+    std::atomic<long> mIntervalMs;
+    std::atomic<long> mLocationIntervalMs;
     std::atomic<bool> mIsActive;
+    std::atomic<bool> mLocationEnabled;
     std::thread mThread;
+    std::vector<std::future<void>> mFutures;
+    ::android::hardware::gnss::common::ThreadBlocker mThreadBlocker;
 
     // Guarded by mMutex
     static std::shared_ptr<IGnssMeasurementCallback> sCallback;
diff --git a/gnss/aidl/default/GnssNavigationMessageInterface.cpp b/gnss/aidl/default/GnssNavigationMessageInterface.cpp
index 4bc859d..75b9624 100644
--- a/gnss/aidl/default/GnssNavigationMessageInterface.cpp
+++ b/gnss/aidl/default/GnssNavigationMessageInterface.cpp
@@ -32,7 +32,7 @@
 GnssNavigationMessageInterface::GnssNavigationMessageInterface() : mMinIntervalMillis(1000) {}
 
 GnssNavigationMessageInterface::~GnssNavigationMessageInterface() {
-    stop();
+    waitForStoppingThreads();
 }
 
 ndk::ScopedAStatus GnssNavigationMessageInterface::setCallback(
@@ -46,7 +46,9 @@
 
 ndk::ScopedAStatus GnssNavigationMessageInterface::close() {
     ALOGD("close");
-    stop();
+    if (mIsActive) {
+        stop();
+    }
     std::unique_lock<std::mutex> lock(mMutex);
     sCallback = nullptr;
     return ndk::ScopedAStatus::ok();
@@ -54,9 +56,20 @@
 
 void GnssNavigationMessageInterface::start() {
     ALOGD("start");
+
+    if (mIsActive) {
+        ALOGD("restarting since nav msg has started");
+        stop();
+    }
+    // Wait for stopping previous thread.
+    waitForStoppingThreads();
+
     mIsActive = true;
     mThread = std::thread([this]() {
-        while (mIsActive == true) {
+        do {
+            if (!mIsActive) {
+                break;
+            }
             GnssNavigationMessage message = {
                     .svid = 19,
                     .type = GnssNavigationMessageType::GPS_L1CA,
@@ -66,15 +79,18 @@
                     .data = std::vector<uint8_t>(40, 0xF9),
             };
             this->reportMessage(message);
-            std::this_thread::sleep_for(std::chrono::milliseconds(mMinIntervalMillis));
-        }
+        } while (mIsActive &&
+                 mThreadBlocker.wait_for(std::chrono::milliseconds(mMinIntervalMillis)));
     });
-    mThread.detach();
 }
 
 void GnssNavigationMessageInterface::stop() {
     ALOGD("stop");
     mIsActive = false;
+    mThreadBlocker.notify();
+    if (mThread.joinable()) {
+        mFutures.push_back(std::async(std::launch::async, [this] { mThread.join(); }));
+    }
 }
 
 void GnssNavigationMessageInterface::reportMessage(const GnssNavigationMessage& message) {
@@ -91,4 +107,13 @@
     callbackCopy->gnssNavigationMessageCb(message);
 }
 
+void GnssNavigationMessageInterface::waitForStoppingThreads() {
+    for (auto& future : mFutures) {
+        ALOGD("Stopping previous thread.");
+        future.wait();
+        ALOGD("Done stopping thread.");
+    }
+    mFutures.clear();
+}
+
 }  // namespace aidl::android::hardware::gnss
diff --git a/gnss/aidl/default/GnssNavigationMessageInterface.h b/gnss/aidl/default/GnssNavigationMessageInterface.h
index 600b23a..b335348 100644
--- a/gnss/aidl/default/GnssNavigationMessageInterface.h
+++ b/gnss/aidl/default/GnssNavigationMessageInterface.h
@@ -18,7 +18,9 @@
 
 #include <aidl/android/hardware/gnss/BnGnssNavigationMessageInterface.h>
 #include <atomic>
+#include <future>
 #include <thread>
+#include "Utils.h"
 
 namespace aidl::android::hardware::gnss {
 
@@ -34,10 +36,13 @@
     void start();
     void stop();
     void reportMessage(const IGnssNavigationMessageCallback::GnssNavigationMessage& message);
+    void waitForStoppingThreads();
 
     std::atomic<long> mMinIntervalMillis;
     std::atomic<bool> mIsActive;
     std::thread mThread;
+    std::vector<std::future<void>> mFutures;
+    ::android::hardware::gnss::common::ThreadBlocker mThreadBlocker;
 
     // Guarded by mMutex
     static std::shared_ptr<IGnssNavigationMessageCallback> sCallback;
diff --git a/gnss/aidl/vts/GnssCallbackAidl.cpp b/gnss/aidl/vts/GnssCallbackAidl.cpp
index 77a2506..2f6128b 100644
--- a/gnss/aidl/vts/GnssCallbackAidl.cpp
+++ b/gnss/aidl/vts/GnssCallbackAidl.cpp
@@ -31,7 +31,7 @@
 }
 
 Status GnssCallbackAidl::gnssStatusCb(const GnssStatusValue /* status */) {
-    ALOGI("gnssSvStatusCb");
+    ALOGI("gnssStatusCb");
     return Status::ok();
 }
 
@@ -47,7 +47,8 @@
     return Status::ok();
 }
 
-Status GnssCallbackAidl::gnssNmeaCb(const int64_t /* timestamp */, const std::string& /* nmea */) {
+Status GnssCallbackAidl::gnssNmeaCb(const int64_t timestamp, const std::string& nmea) {
+    nmea_cbq_.store(std::make_pair(timestamp, nmea));
     return Status::ok();
 }
 
diff --git a/gnss/aidl/vts/GnssCallbackAidl.h b/gnss/aidl/vts/GnssCallbackAidl.h
index 209728d..a9495ba 100644
--- a/gnss/aidl/vts/GnssCallbackAidl.h
+++ b/gnss/aidl/vts/GnssCallbackAidl.h
@@ -17,6 +17,7 @@
 #pragma once
 
 #include <android/hardware/gnss/BnGnssCallback.h>
+#include <utility>
 #include "GnssCallbackEventQueue.h"
 
 /* Callback class for data & Event. */
@@ -26,7 +27,8 @@
         : capabilities_cbq_("capabilities"),
           info_cbq_("system_info"),
           location_cbq_("location"),
-          sv_info_list_cbq_("sv_info"){};
+          sv_info_list_cbq_("sv_info"),
+          nmea_cbq_("nmea"){};
     ~GnssCallbackAidl(){};
 
     android::binder::Status gnssSetCapabilitiesCb(const int capabilities) override;
@@ -55,4 +57,6 @@
     android::hardware::gnss::common::GnssCallbackEventQueue<
             std::vector<android::hardware::gnss::IGnssCallback::GnssSvInfo>>
             sv_info_list_cbq_;
+    android::hardware::gnss::common::GnssCallbackEventQueue<std::pair<int64_t, std::string>>
+            nmea_cbq_;
 };
\ No newline at end of file
diff --git a/gnss/aidl/vts/GnssMeasurementCallbackAidl.cpp b/gnss/aidl/vts/GnssMeasurementCallbackAidl.cpp
index c4fad7f..a553954 100644
--- a/gnss/aidl/vts/GnssMeasurementCallbackAidl.cpp
+++ b/gnss/aidl/vts/GnssMeasurementCallbackAidl.cpp
@@ -24,12 +24,10 @@
 
 android::binder::Status GnssMeasurementCallbackAidl::gnssMeasurementCb(const GnssData& gnssData) {
     ALOGI("gnssMeasurementCb");
-    ALOGI("elapsedRealtime: flags = %d, timestampNs: %" PRId64 ", timeUncertaintyNs=%lf",
+    ALOGV("elapsedRealtime: flags = 0x%X, timestampNs: %" PRId64 ", timeUncertaintyNs=%lf",
           gnssData.elapsedRealtime.flags, gnssData.elapsedRealtime.timestampNs,
           gnssData.elapsedRealtime.timeUncertaintyNs);
-    for (const auto& measurement : gnssData.measurements) {
-        ALOGI("measurement.receivedSvTimeInNs=%" PRId64, measurement.receivedSvTimeInNs);
-    }
+
     gnss_data_cbq_.store(gnssData);
     return android::binder::Status::ok();
 }
diff --git a/gnss/aidl/vts/gnss_hal_test.cpp b/gnss/aidl/vts/gnss_hal_test.cpp
index f184f81..0e1218e 100644
--- a/gnss/aidl/vts/gnss_hal_test.cpp
+++ b/gnss/aidl/vts/gnss_hal_test.cpp
@@ -18,15 +18,50 @@
 
 #include "gnss_hal_test.h"
 #include <hidl/ServiceManagement.h>
+#include <algorithm>
+#include <cmath>
 #include "Utils.h"
 
+using android::hardware::gnss::GnssClock;
 using android::hardware::gnss::GnssConstellationType;
+using android::hardware::gnss::GnssData;
 using android::hardware::gnss::GnssLocation;
+using android::hardware::gnss::GnssMeasurement;
 using android::hardware::gnss::IGnss;
 using android::hardware::gnss::IGnssCallback;
+using android::hardware::gnss::IGnssMeasurementInterface;
 using android::hardware::gnss::common::Utils;
 using GnssConstellationTypeV2_0 = android::hardware::gnss::V2_0::GnssConstellationType;
 
+namespace {
+// The difference between the mean of the received intervals and the requested interval should not
+// be larger mInterval * ALLOWED_MEAN_ERROR_RATIO
+constexpr double ALLOWED_MEAN_ERROR_RATIO = 0.25;
+
+// The standard deviation computed for the deltas should not be bigger
+// than mInterval * ALLOWED_STDEV_ERROR_RATIO or MIN_STDEV_MS, whichever is higher.
+constexpr double ALLOWED_STDEV_ERROR_RATIO = 0.50;
+constexpr double MIN_STDEV_MS = 1000;
+
+double computeMean(std::vector<int>& deltas) {
+    long accumulator = 0;
+    for (auto& d : deltas) {
+        accumulator += d;
+    }
+    return accumulator / deltas.size();
+}
+
+double computeStdev(double mean, std::vector<int>& deltas) {
+    double accumulator = 0;
+    for (auto& d : deltas) {
+        double diff = d - mean;
+        accumulator += diff * diff;
+    }
+    return std::sqrt(accumulator / (deltas.size() - 1));
+}
+
+}  // anonymous namespace
+
 void GnssHalTest::SetUp() {
     // Get AIDL handle
     aidl_gnss_hal_ = android::waitForDeclaredService<IGnssAidl>(String16(GetParam().c_str()));
@@ -97,19 +132,25 @@
     ASSERT_TRUE(status.isOk());
 }
 
-bool GnssHalTest::StartAndCheckFirstLocation(const int min_interval_msec,
-                                             const bool low_power_mode) {
+bool GnssHalTest::StartAndCheckFirstLocation(const int min_interval_msec, const bool low_power_mode,
+                                             const bool start_sv_status, const bool start_nmea) {
     if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
         // Invoke the super method.
         return GnssHalTestTemplate<IGnss_V2_1>::StartAndCheckFirstLocation(min_interval_msec,
                                                                            low_power_mode);
     }
-
     SetPositionMode(min_interval_msec, low_power_mode);
-    auto status = aidl_gnss_hal_->start();
-    EXPECT_TRUE(status.isOk());
 
-    status = aidl_gnss_hal_->startSvStatus();
+    if (start_sv_status) {
+        auto status = aidl_gnss_hal_->startSvStatus();
+        EXPECT_TRUE(status.isOk());
+    }
+    if (start_nmea) {
+        auto status = aidl_gnss_hal_->startNmea();
+        EXPECT_TRUE(status.isOk());
+    }
+
+    auto status = aidl_gnss_hal_->start();
     EXPECT_TRUE(status.isOk());
 
     /*
@@ -131,6 +172,12 @@
     return false;
 }
 
+bool GnssHalTest::StartAndCheckFirstLocation(const int min_interval_msec,
+                                             const bool low_power_mode) {
+    return StartAndCheckFirstLocation(min_interval_msec, low_power_mode,
+                                      /* start_sv_status= */ true, /* start_nmea= */ true);
+}
+
 void GnssHalTest::StopAndClearLocations() {
     ALOGD("StopAndClearLocations");
     if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
@@ -139,6 +186,8 @@
     }
     auto status = aidl_gnss_hal_->stopSvStatus();
     EXPECT_TRUE(status.isOk());
+    status = aidl_gnss_hal_->stopNmea();
+    EXPECT_TRUE(status.isOk());
 
     status = aidl_gnss_hal_->stop();
     EXPECT_TRUE(status.isOk());
@@ -153,7 +202,8 @@
     aidl_gnss_cb_->location_cbq_.reset();
 }
 
-void GnssHalTest::StartAndCheckLocations(int count) {
+void GnssHalTest::StartAndCheckLocations(const int count, const bool start_sv_status,
+                                         const bool start_nmea) {
     if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
         // Invoke the super method.
         return GnssHalTestTemplate<IGnss_V2_1>::StartAndCheckLocations(count);
@@ -162,7 +212,8 @@
     const int kLocationTimeoutSubsequentSec = 2;
     const bool kLowPowerMode = false;
 
-    EXPECT_TRUE(StartAndCheckFirstLocation(kMinIntervalMsec, kLowPowerMode));
+    EXPECT_TRUE(StartAndCheckFirstLocation(kMinIntervalMsec, kLowPowerMode, start_sv_status,
+                                           start_nmea));
 
     for (int i = 1; i < count; i++) {
         EXPECT_TRUE(aidl_gnss_cb_->location_cbq_.retrieve(aidl_gnss_cb_->last_location_,
@@ -177,6 +228,10 @@
     }
 }
 
+void GnssHalTest::StartAndCheckLocations(const int count) {
+    StartAndCheckLocations(count, /* start_sv_status= */ true, /* start_nmea= */ true);
+}
+
 std::list<std::vector<IGnssCallback::GnssSvInfo>> GnssHalTest::convertToAidl(
         const std::list<hidl_vec<IGnssCallback_2_1::GnssSvInfo>>& sv_info_list) {
     std::list<std::vector<IGnssCallback::GnssSvInfo>> aidl_sv_info_list;
@@ -313,3 +368,109 @@
 
     return constellation_to_blocklist;
 }
+
+void GnssHalTest::checkGnssMeasurementClockFields(const GnssData& measurement) {
+    Utils::checkElapsedRealtime(measurement.elapsedRealtime);
+    ASSERT_TRUE(measurement.clock.gnssClockFlags >= 0 &&
+                measurement.clock.gnssClockFlags <=
+                        (GnssClock::HAS_LEAP_SECOND | GnssClock::HAS_TIME_UNCERTAINTY |
+                         GnssClock::HAS_FULL_BIAS | GnssClock::HAS_BIAS |
+                         GnssClock::HAS_BIAS_UNCERTAINTY | GnssClock::HAS_DRIFT |
+                         GnssClock::HAS_DRIFT_UNCERTAINTY));
+}
+
+void GnssHalTest::checkGnssMeasurementFlags(const GnssMeasurement& measurement) {
+    ASSERT_TRUE(measurement.flags >= 0 &&
+                measurement.flags <=
+                        (GnssMeasurement::HAS_SNR | GnssMeasurement::HAS_CARRIER_FREQUENCY |
+                         GnssMeasurement::HAS_CARRIER_CYCLES | GnssMeasurement::HAS_CARRIER_PHASE |
+                         GnssMeasurement::HAS_CARRIER_PHASE_UNCERTAINTY |
+                         GnssMeasurement::HAS_AUTOMATIC_GAIN_CONTROL |
+                         GnssMeasurement::HAS_FULL_ISB | GnssMeasurement::HAS_FULL_ISB_UNCERTAINTY |
+                         GnssMeasurement::HAS_SATELLITE_ISB |
+                         GnssMeasurement::HAS_SATELLITE_ISB_UNCERTAINTY |
+                         GnssMeasurement::HAS_SATELLITE_PVT |
+                         GnssMeasurement::HAS_CORRELATION_VECTOR));
+}
+
+void GnssHalTest::checkGnssMeasurementFields(const GnssMeasurement& measurement,
+                                             const GnssData& data) {
+    checkGnssMeasurementFlags(measurement);
+    // Verify CodeType is valid.
+    ASSERT_NE(measurement.signalType.codeType, "");
+    // Verify basebandCn0DbHz is valid.
+    ASSERT_TRUE(measurement.basebandCN0DbHz > 0.0 && measurement.basebandCN0DbHz <= 65.0);
+
+    if (((measurement.flags & GnssMeasurement::HAS_FULL_ISB) > 0) &&
+        ((measurement.flags & GnssMeasurement::HAS_FULL_ISB_UNCERTAINTY) > 0) &&
+        ((measurement.flags & GnssMeasurement::HAS_SATELLITE_ISB) > 0) &&
+        ((measurement.flags & GnssMeasurement::HAS_SATELLITE_ISB_UNCERTAINTY) > 0)) {
+        GnssConstellationType referenceConstellation =
+                data.clock.referenceSignalTypeForIsb.constellation;
+        double carrierFrequencyHz = data.clock.referenceSignalTypeForIsb.carrierFrequencyHz;
+        std::string codeType = data.clock.referenceSignalTypeForIsb.codeType;
+
+        ASSERT_TRUE(referenceConstellation >= GnssConstellationType::UNKNOWN &&
+                    referenceConstellation <= GnssConstellationType::IRNSS);
+        ASSERT_TRUE(carrierFrequencyHz > 0);
+        ASSERT_NE(codeType, "");
+
+        ASSERT_TRUE(std::abs(measurement.fullInterSignalBiasNs) < 1.0e6);
+        ASSERT_TRUE(measurement.fullInterSignalBiasUncertaintyNs >= 0);
+        ASSERT_TRUE(std::abs(measurement.satelliteInterSignalBiasNs) < 1.0e6);
+        ASSERT_TRUE(measurement.satelliteInterSignalBiasUncertaintyNs >= 0);
+    }
+}
+
+void GnssHalTest::startMeasurementWithInterval(
+        int intervalMs, const sp<IGnssMeasurementInterface>& iGnssMeasurement,
+        sp<GnssMeasurementCallbackAidl>& callback) {
+    ALOGD("Start requesting measurement at interval of %d millis.", intervalMs);
+    IGnssMeasurementInterface::Options options;
+    options.intervalMs = intervalMs;
+    auto status = iGnssMeasurement->setCallbackWithOptions(callback, options);
+    ASSERT_TRUE(status.isOk());
+}
+
+void GnssHalTest::collectMeasurementIntervals(const sp<GnssMeasurementCallbackAidl>& callback,
+                                              const int numMeasurementEvents,
+                                              const int timeoutSeconds,
+                                              std::vector<int>& deltasMs) {
+    int64_t lastElapsedRealtimeMillis = 0;
+    for (int i = 0; i < numMeasurementEvents; i++) {
+        GnssData lastGnssData;
+        ASSERT_TRUE(callback->gnss_data_cbq_.retrieve(lastGnssData, timeoutSeconds));
+        EXPECT_EQ(callback->gnss_data_cbq_.calledCount(), i + 1);
+        ASSERT_TRUE(lastGnssData.measurements.size() > 0);
+
+        // Validity check GnssData fields
+        checkGnssMeasurementClockFields(lastGnssData);
+        for (const auto& measurement : lastGnssData.measurements) {
+            checkGnssMeasurementFields(measurement, lastGnssData);
+        }
+
+        long currentElapsedRealtimeMillis = lastGnssData.elapsedRealtime.timestampNs * 1e-6;
+        if (lastElapsedRealtimeMillis != 0) {
+            deltasMs.push_back(currentElapsedRealtimeMillis - lastElapsedRealtimeMillis);
+        }
+        lastElapsedRealtimeMillis = currentElapsedRealtimeMillis;
+    }
+}
+
+void GnssHalTest::assertMeanAndStdev(int intervalMs, std::vector<int>& deltasMs) {
+    double mean = computeMean(deltasMs);
+    double stdev = computeStdev(mean, deltasMs);
+    EXPECT_TRUE(std::abs(mean - intervalMs) <= intervalMs * ALLOWED_MEAN_ERROR_RATIO)
+            << "Test failed, because the mean of intervals is " << mean
+            << " millis. The test requires that abs(" << mean << " - " << intervalMs
+            << ") <= " << intervalMs * ALLOWED_MEAN_ERROR_RATIO
+            << " millis, when the requested interval is " << intervalMs << " millis.";
+
+    double maxStdev = std::max(MIN_STDEV_MS, intervalMs * ALLOWED_STDEV_ERROR_RATIO);
+    EXPECT_TRUE(stdev <= maxStdev)
+            << "Test failed, because the stdev of intervals is " << stdev
+            << " millis, which must be <= " << maxStdev
+            << " millis, when the requested interval is " << intervalMs << " millis.";
+    ALOGD("Mean of interval deltas in millis: %.1lf", mean);
+    ALOGD("Stdev of interval deltas in millis: %.1lf", stdev);
+}
diff --git a/gnss/aidl/vts/gnss_hal_test.h b/gnss/aidl/vts/gnss_hal_test.h
index d479af3..645fc82 100644
--- a/gnss/aidl/vts/gnss_hal_test.h
+++ b/gnss/aidl/vts/gnss_hal_test.h
@@ -25,6 +25,7 @@
 #include <android/hardware/gnss/2.1/IGnss.h>
 #include "GnssBatchingCallback.h"
 #include "GnssCallbackAidl.h"
+#include "GnssMeasurementCallbackAidl.h"
 #include "v2_1/gnss_hal_test_template.h"
 
 using IGnss_V2_1 = android::hardware::gnss::V2_1::IGnss;
@@ -68,8 +69,11 @@
                        const bool check_speed);
     void SetPositionMode(const int min_interval_msec, const bool low_power_mode);
     bool StartAndCheckFirstLocation(const int min_interval_msec, const bool low_power_mode);
+    bool StartAndCheckFirstLocation(const int min_interval_msec, const bool low_power_mode,
+                                    const bool start_sv_status, const bool start_nmea);
     void StopAndClearLocations();
-    void StartAndCheckLocations(int count);
+    void StartAndCheckLocations(const int count);
+    void StartAndCheckLocations(const int count, const bool start_sv_status, const bool start_nmea);
 
     android::hardware::gnss::GnssConstellationType startLocationAndGetNonGpsConstellation(
             const int locations_to_await, const int gnss_sv_info_list_timeout);
@@ -85,6 +89,19 @@
                     sv_info_list,
             const int min_observations);
 
+    void checkGnssMeasurementClockFields(const android::hardware::gnss::GnssData& measurement);
+    void checkGnssMeasurementFlags(const android::hardware::gnss::GnssMeasurement& measurement);
+    void checkGnssMeasurementFields(const android::hardware::gnss::GnssMeasurement& measurement,
+                                    const android::hardware::gnss::GnssData& data);
+    void startMeasurementWithInterval(
+            int intervalMillis,
+            const sp<android::hardware::gnss::IGnssMeasurementInterface>& iMeasurement,
+            sp<GnssMeasurementCallbackAidl>& callback);
+    void collectMeasurementIntervals(const sp<GnssMeasurementCallbackAidl>& callback,
+                                     const int numMeasurementEvents, const int timeoutSeconds,
+                                     std::vector<int>& deltaMs);
+    void assertMeanAndStdev(int intervalMillis, std::vector<int>& deltasMillis);
+
     sp<IGnssAidl> aidl_gnss_hal_;
     sp<GnssCallbackAidl> aidl_gnss_cb_;  // Primary callback interface
 };
diff --git a/gnss/aidl/vts/gnss_hal_test_cases.cpp b/gnss/aidl/vts/gnss_hal_test_cases.cpp
index 54946fb..3696233 100644
--- a/gnss/aidl/vts/gnss_hal_test_cases.cpp
+++ b/gnss/aidl/vts/gnss_hal_test_cases.cpp
@@ -28,7 +28,9 @@
 #include <android/hardware/gnss/measurement_corrections/IMeasurementCorrectionsInterface.h>
 #include <android/hardware/gnss/visibility_control/IGnssVisibilityControl.h>
 #include <cutils/properties.h>
+#include <utils/SystemClock.h>
 #include <cmath>
+#include <utility>
 #include "AGnssCallbackAidl.h"
 #include "AGnssRilCallbackAidl.h"
 #include "GnssAntennaInfoCallbackAidl.h"
@@ -289,10 +291,12 @@
         EXPECT_GT(aidl_gnss_cb_->sv_info_list_cbq_.retrieve(sv_info_lists, kNumSvInfoLists,
                                                             kTimeoutSeconds),
                   0);
-        last_sv_info_list = sv_info_lists.back();
-    } while (last_sv_info_list.size() == 0);
+        if (!sv_info_lists.empty()) {
+            last_sv_info_list = sv_info_lists.back();
+            ALOGD("last_sv_info size = %d", (int)last_sv_info_list.size());
+        }
+    } while (!sv_info_lists.empty() && last_sv_info_list.size() == 0);
 
-    ALOGD("last_sv_info size = %d", (int)last_sv_info_list.size());
     bool nonZeroCn0Found = false;
     for (auto sv_info : last_sv_info_list) {
         EXPECT_TRUE(sv_info.basebandCN0DbHz >= 0.0 && sv_info.basebandCN0DbHz <= 65.0);
@@ -376,58 +380,6 @@
     }
 }
 
-void CheckGnssMeasurementClockFields(const GnssData& measurement) {
-    Utils::checkElapsedRealtime(measurement.elapsedRealtime);
-    ASSERT_TRUE(measurement.clock.gnssClockFlags >= 0 &&
-                measurement.clock.gnssClockFlags <=
-                        (GnssClock::HAS_LEAP_SECOND | GnssClock::HAS_TIME_UNCERTAINTY |
-                         GnssClock::HAS_FULL_BIAS | GnssClock::HAS_BIAS |
-                         GnssClock::HAS_BIAS_UNCERTAINTY | GnssClock::HAS_DRIFT |
-                         GnssClock::HAS_DRIFT_UNCERTAINTY));
-}
-
-void CheckGnssMeasurementFlags(const GnssMeasurement& measurement) {
-    ASSERT_TRUE(measurement.flags >= 0 &&
-                measurement.flags <=
-                        (GnssMeasurement::HAS_SNR | GnssMeasurement::HAS_CARRIER_FREQUENCY |
-                         GnssMeasurement::HAS_CARRIER_CYCLES | GnssMeasurement::HAS_CARRIER_PHASE |
-                         GnssMeasurement::HAS_CARRIER_PHASE_UNCERTAINTY |
-                         GnssMeasurement::HAS_AUTOMATIC_GAIN_CONTROL |
-                         GnssMeasurement::HAS_FULL_ISB | GnssMeasurement::HAS_FULL_ISB_UNCERTAINTY |
-                         GnssMeasurement::HAS_SATELLITE_ISB |
-                         GnssMeasurement::HAS_SATELLITE_ISB_UNCERTAINTY |
-                         GnssMeasurement::HAS_SATELLITE_PVT |
-                         GnssMeasurement::HAS_CORRELATION_VECTOR));
-}
-
-void CheckGnssMeasurementFields(const GnssMeasurement& measurement, const GnssData& data) {
-    CheckGnssMeasurementFlags(measurement);
-    // Verify CodeType is valid.
-    ASSERT_NE(measurement.signalType.codeType, "");
-    // Verify basebandCn0DbHz is valid.
-    ASSERT_TRUE(measurement.basebandCN0DbHz > 0.0 && measurement.basebandCN0DbHz <= 65.0);
-
-    if (((measurement.flags & GnssMeasurement::HAS_FULL_ISB) > 0) &&
-        ((measurement.flags & GnssMeasurement::HAS_FULL_ISB_UNCERTAINTY) > 0) &&
-        ((measurement.flags & GnssMeasurement::HAS_SATELLITE_ISB) > 0) &&
-        ((measurement.flags & GnssMeasurement::HAS_SATELLITE_ISB_UNCERTAINTY) > 0)) {
-        GnssConstellationType referenceConstellation =
-                data.clock.referenceSignalTypeForIsb.constellation;
-        double carrierFrequencyHz = data.clock.referenceSignalTypeForIsb.carrierFrequencyHz;
-        std::string codeType = data.clock.referenceSignalTypeForIsb.codeType;
-
-        ASSERT_TRUE(referenceConstellation >= GnssConstellationType::UNKNOWN &&
-                    referenceConstellation <= GnssConstellationType::IRNSS);
-        ASSERT_TRUE(carrierFrequencyHz > 0);
-        ASSERT_NE(codeType, "");
-
-        ASSERT_TRUE(std::abs(measurement.fullInterSignalBiasNs) < 1.0e6);
-        ASSERT_TRUE(measurement.fullInterSignalBiasUncertaintyNs >= 0);
-        ASSERT_TRUE(std::abs(measurement.satelliteInterSignalBiasNs) < 1.0e6);
-        ASSERT_TRUE(measurement.satelliteInterSignalBiasUncertaintyNs >= 0);
-    }
-}
-
 /*
  * TestGnssMeasurementExtensionAndSatellitePvt:
  * 1. Gets the GnssMeasurementExtension and verifies that it returns a non-null extension.
@@ -465,10 +417,10 @@
         ASSERT_TRUE(lastMeasurement.measurements.size() > 0);
 
         // Validity check GnssData fields
-        CheckGnssMeasurementClockFields(lastMeasurement);
+        checkGnssMeasurementClockFields(lastMeasurement);
 
         for (const auto& measurement : lastMeasurement.measurements) {
-            CheckGnssMeasurementFields(measurement, lastMeasurement);
+            checkGnssMeasurementFields(measurement, lastMeasurement);
             if (measurement.flags & GnssMeasurement::HAS_SATELLITE_PVT &&
                 kIsSatellitePvtSupported == true) {
                 ALOGD("Found a measurement with SatellitePvt");
@@ -525,10 +477,10 @@
         ASSERT_TRUE(lastMeasurement.measurements.size() > 0);
 
         // Validity check GnssData fields
-        CheckGnssMeasurementClockFields(lastMeasurement);
+        checkGnssMeasurementClockFields(lastMeasurement);
 
         for (const auto& measurement : lastMeasurement.measurements) {
-            CheckGnssMeasurementFields(measurement, lastMeasurement);
+            checkGnssMeasurementFields(measurement, lastMeasurement);
             if (measurement.flags & GnssMeasurement::HAS_CORRELATION_VECTOR) {
                 correlationVectorFound = true;
                 ASSERT_TRUE(measurement.correlationVectors.size() > 0);
@@ -1242,48 +1194,6 @@
 }
 
 /*
- * TestGnssMeasurementSetCallbackWithOptions:
- * 1. Gets the GnssMeasurementExtension and verifies that it returns a non-null extension.
- * 2. Sets a GnssMeasurementCallback with intervalMillis option, waits for measurements reported,
- *    and verifies mandatory fields are valid.
- */
-TEST_P(GnssHalTest, TestGnssMeasurementSetCallbackWithOptions) {
-    if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
-        return;
-    }
-    const int kFirstGnssMeasurementTimeoutSeconds = 10;
-    const int kNumMeasurementEvents = 5;
-
-    sp<IGnssMeasurementInterface> iGnssMeasurement;
-    auto status = aidl_gnss_hal_->getExtensionGnssMeasurement(&iGnssMeasurement);
-    ASSERT_TRUE(status.isOk());
-    ASSERT_TRUE(iGnssMeasurement != nullptr);
-
-    auto callback = sp<GnssMeasurementCallbackAidl>::make();
-    IGnssMeasurementInterface::Options options;
-    options.intervalMs = 2000;
-    status = iGnssMeasurement->setCallbackWithOptions(callback, options);
-    ASSERT_TRUE(status.isOk());
-
-    for (int i = 0; i < kNumMeasurementEvents; i++) {
-        GnssData lastMeasurement;
-        ASSERT_TRUE(callback->gnss_data_cbq_.retrieve(lastMeasurement,
-                                                      kFirstGnssMeasurementTimeoutSeconds));
-        EXPECT_EQ(callback->gnss_data_cbq_.calledCount(), i + 1);
-        ASSERT_TRUE(lastMeasurement.measurements.size() > 0);
-
-        // Validity check GnssData fields
-        CheckGnssMeasurementClockFields(lastMeasurement);
-        for (const auto& measurement : lastMeasurement.measurements) {
-            CheckGnssMeasurementFields(measurement, lastMeasurement);
-        }
-    }
-
-    status = iGnssMeasurement->close();
-    ASSERT_TRUE(status.isOk());
-}
-
-/*
  * TestGnssAgcInGnssMeasurement:
  * 1. Gets the GnssMeasurementExtension and verifies that it returns a non-null extension.
  * 2. Sets a GnssMeasurementCallback, waits for a measurement.
@@ -1293,7 +1203,7 @@
         return;
     }
     const int kFirstGnssMeasurementTimeoutSeconds = 10;
-    const int kNumMeasurementEvents = 15;
+    const int kNumMeasurementEvents = 5;
 
     sp<IGnssMeasurementInterface> iGnssMeasurement;
     auto status = aidl_gnss_hal_->getExtensionGnssMeasurement(&iGnssMeasurement);
@@ -1313,7 +1223,7 @@
         ASSERT_TRUE(lastMeasurement.measurements.size() > 0);
 
         // Validity check GnssData fields
-        CheckGnssMeasurementClockFields(lastMeasurement);
+        checkGnssMeasurementClockFields(lastMeasurement);
 
         ASSERT_TRUE(lastMeasurement.gnssAgcs.size() > 0);
         for (const auto& gnssAgc : lastMeasurement.gnssAgcs) {
@@ -1444,3 +1354,143 @@
             Utils::getMockMeasurementCorrections_aidl());
     ASSERT_TRUE(status.isOk());
 }
+
+/*
+ * TestStopSvStatusAndNmea:
+ * 1. Call stopSvStatus and stopNmea.
+ * 2. Start location and verify that
+ *    - no SvStatus is received.
+ *    - no Nmea is received.
+ */
+TEST_P(GnssHalTest, TestStopSvStatusAndNmea) {
+    if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
+        return;
+    }
+    auto status = aidl_gnss_hal_->stopSvStatus();
+    EXPECT_TRUE(status.isOk());
+    status = aidl_gnss_hal_->stopNmea();
+    EXPECT_TRUE(status.isOk());
+
+    int kLocationsToAwait = 5;
+    aidl_gnss_cb_->location_cbq_.reset();
+    aidl_gnss_cb_->sv_info_list_cbq_.reset();
+    aidl_gnss_cb_->nmea_cbq_.reset();
+    StartAndCheckLocations(/* count= */ kLocationsToAwait,
+                           /* start_sv_status= */ false, /* start_nmea= */ false);
+    int location_called_count = aidl_gnss_cb_->location_cbq_.calledCount();
+    ALOGD("Observed %d GnssSvStatus, and %d Nmea while awaiting %d locations (%d received)",
+          aidl_gnss_cb_->sv_info_list_cbq_.size(), aidl_gnss_cb_->nmea_cbq_.size(),
+          kLocationsToAwait, location_called_count);
+
+    // Ensure that no SvStatus & no Nmea is received.
+    EXPECT_EQ(aidl_gnss_cb_->sv_info_list_cbq_.size(), 0);
+    EXPECT_EQ(aidl_gnss_cb_->nmea_cbq_.size(), 0);
+
+    StopAndClearLocations();
+}
+
+/*
+ * TestGnssMeasurementIntervals_WithoutLocation:
+ * 1. start measurement with interval
+ * 2. verify that the received measurement intervals have expected mean and stdev
+ */
+TEST_P(GnssHalTest, TestGnssMeasurementIntervals_WithoutLocation) {
+    if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
+        return;
+    }
+
+    std::vector<int> intervals({2000, 4000});
+    std::vector<int> numEvents({10, 5});
+
+    sp<IGnssMeasurementInterface> iGnssMeasurement;
+    auto status = aidl_gnss_hal_->getExtensionGnssMeasurement(&iGnssMeasurement);
+    ASSERT_TRUE(status.isOk());
+    ASSERT_TRUE(iGnssMeasurement != nullptr);
+
+    ALOGD("TestGnssMeasurementIntervals_WithoutLocation");
+    for (int i = 0; i < intervals.size(); i++) {
+        auto callback = sp<GnssMeasurementCallbackAidl>::make();
+        startMeasurementWithInterval(intervals[i], iGnssMeasurement, callback);
+
+        std::vector<int> deltas;
+        collectMeasurementIntervals(callback, numEvents[i], /* timeoutSeconds= */ 10, deltas);
+
+        status = iGnssMeasurement->close();
+        ASSERT_TRUE(status.isOk());
+
+        assertMeanAndStdev(intervals[i], deltas);
+    }
+}
+
+/*
+ * TestGnssMeasurementIntervals_LocationOnBeforeMeasurement:
+ * 1. start measurement with interval
+ * 2. verify that the received measurement intervals have expected mean and stdev
+ */
+TEST_P(GnssHalTest, TestGnssMeasurementIntervals_LocationOnBeforeMeasurement) {
+    if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
+        return;
+    }
+
+    std::vector<int> intervals({2000});
+
+    sp<IGnssMeasurementInterface> iGnssMeasurement;
+    auto status = aidl_gnss_hal_->getExtensionGnssMeasurement(&iGnssMeasurement);
+    ASSERT_TRUE(status.isOk());
+    ASSERT_TRUE(iGnssMeasurement != nullptr);
+
+    int locationIntervalMs = 1000;
+
+    // Start location first and then start measurement
+    ALOGD("TestGnssMeasurementIntervals_LocationOnBeforeMeasurement");
+    StartAndCheckFirstLocation(locationIntervalMs, /* lowPowerMode= */ false);
+    for (auto& intervalMs : intervals) {
+        auto callback = sp<GnssMeasurementCallbackAidl>::make();
+        startMeasurementWithInterval(intervalMs, iGnssMeasurement, callback);
+
+        std::vector<int> deltas;
+        collectMeasurementIntervals(callback, /*numEvents=*/10, /*timeoutSeconds=*/10, deltas);
+
+        status = iGnssMeasurement->close();
+        ASSERT_TRUE(status.isOk());
+
+        assertMeanAndStdev(locationIntervalMs, deltas);
+    }
+    StopAndClearLocations();
+}
+
+/*
+ * TestGnssMeasurementIntervals:
+ * 1. start measurement with interval
+ * 2. verify that the received measurement intervals have expected mean and stdev
+ */
+TEST_P(GnssHalTest, TestGnssMeasurementIntervals_LocationOnAfterMeasurement) {
+    if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
+        return;
+    }
+
+    std::vector<int> intervals({2000});
+
+    sp<IGnssMeasurementInterface> iGnssMeasurement;
+    auto status = aidl_gnss_hal_->getExtensionGnssMeasurement(&iGnssMeasurement);
+    ASSERT_TRUE(status.isOk());
+    ASSERT_TRUE(iGnssMeasurement != nullptr);
+
+    int locationIntervalMs = 1000;
+    // Start location first and then start measurement
+    ALOGD("TestGnssMeasurementIntervals_LocationOnAfterMeasurement");
+    for (auto& intervalMs : intervals) {
+        auto callback = sp<GnssMeasurementCallbackAidl>::make();
+        startMeasurementWithInterval(intervalMs, iGnssMeasurement, callback);
+
+        StartAndCheckFirstLocation(locationIntervalMs, /* lowPowerMode= */ false);
+        std::vector<int> deltas;
+        collectMeasurementIntervals(callback, /*numEvents=*/10, /*timeoutSeconds=*/10, deltas);
+
+        StopAndClearLocations();
+        status = iGnssMeasurement->close();
+        ASSERT_TRUE(status.isOk());
+
+        assertMeanAndStdev(locationIntervalMs, deltas);
+    }
+}
diff --git a/gnss/common/utils/default/include/Utils.h b/gnss/common/utils/default/include/Utils.h
index 7065a6f..ad8f539 100644
--- a/gnss/common/utils/default/include/Utils.h
+++ b/gnss/common/utils/default/include/Utils.h
@@ -56,6 +56,31 @@
     static hidl_vec<V2_1::IGnssAntennaInfoCallback::GnssAntennaInfo> getMockAntennaInfos();
 };
 
+struct ThreadBlocker {
+    // returns false if unblocked:
+    template <class R, class P>
+    bool wait_for(std::chrono::duration<R, P> const& time) {
+        std::unique_lock<std::mutex> lock(m);
+        return !cv.wait_for(lock, time, [&] { return terminate; });
+    }
+
+    void notify() {
+        std::unique_lock<std::mutex> lock(m);
+        terminate = true;
+        cv.notify_all();
+    }
+
+    void reset() {
+        std::unique_lock<std::mutex> lock(m);
+        terminate = false;
+    }
+
+  private:
+    std::condition_variable cv;
+    std::mutex m;
+    bool terminate = false;
+};
+
 }  // namespace common
 }  // namespace gnss
 }  // namespace hardware
diff --git a/graphics/allocator/aidl/vts/VtsHalGraphicsAllocatorAidl_TargetTest.cpp b/graphics/allocator/aidl/vts/VtsHalGraphicsAllocatorAidl_TargetTest.cpp
index c9d058d..59af5cf 100644
--- a/graphics/allocator/aidl/vts/VtsHalGraphicsAllocatorAidl_TargetTest.cpp
+++ b/graphics/allocator/aidl/vts/VtsHalGraphicsAllocatorAidl_TargetTest.cpp
@@ -153,7 +153,6 @@
             if (error == EX_SERVICE_SPECIFIC) {
                 error = status.getServiceSpecificError();
                 EXPECT_NE(OK, error) << "Failed to set error properly";
-                EXPECT_EQ(OK, error) << "Failed to allocate";
             } else {
                 EXPECT_EQ(OK, error) << "Allocation transport failure";
             }
@@ -278,6 +277,7 @@
     if (!supported) {
         ASSERT_EQ(nullptr, buffer.get())
                 << "Allocation succeeded, but IMapper::isSupported was false";
+        GTEST_SKIP();
     } else {
         ASSERT_NE(nullptr, buffer.get()) << "Allocation failed, but IMapper::isSupported was true";
     }
@@ -319,6 +319,7 @@
     if (!supported) {
         ASSERT_EQ(nullptr, buffer.get())
                 << "Allocation succeeded, but IMapper::isSupported was false";
+        GTEST_SKIP();
     } else {
         ASSERT_NE(nullptr, buffer.get()) << "Allocation failed, but IMapper::isSupported was true";
     }
@@ -375,4 +376,4 @@
         [](auto info) -> std::string {
             std::string name = std::to_string(info.index) + "/" + std::get<2>(info.param).name;
             return Sanitize(name);
-        });
\ No newline at end of file
+        });
diff --git a/graphics/composer/2.1/utils/vts/Android.bp b/graphics/composer/2.1/utils/vts/Android.bp
index 8732d53..c0a0c07 100644
--- a/graphics/composer/2.1/utils/vts/Android.bp
+++ b/graphics/composer/2.1/utils/vts/Android.bp
@@ -32,6 +32,7 @@
         "TestCommandReader.cpp",
     ],
     static_libs: [
+        "android.hardware.graphics.allocator-V1-ndk",
         "android.hardware.graphics.composer@2.1",
         "android.hardware.graphics.mapper@2.0-vts",
         "android.hardware.graphics.mapper@3.0-vts",
@@ -39,6 +40,7 @@
         "libgtest",
     ],
     export_static_lib_headers: [
+        "android.hardware.graphics.allocator-V1-ndk",
         "android.hardware.graphics.composer@2.1",
         "android.hardware.graphics.mapper@2.0-vts",
         "android.hardware.graphics.mapper@3.0-vts",
diff --git a/graphics/composer/2.1/utils/vts/ComposerVts.cpp b/graphics/composer/2.1/utils/vts/ComposerVts.cpp
index 55aaf12..4603dd1 100644
--- a/graphics/composer/2.1/utils/vts/ComposerVts.cpp
+++ b/graphics/composer/2.1/utils/vts/ComposerVts.cpp
@@ -316,9 +316,13 @@
 
 Gralloc::Gralloc() {
     [this] {
-        ASSERT_NO_FATAL_FAILURE(mGralloc4 = std::make_shared<Gralloc4>("default", "default",
-                                                                       /*errOnFailure=*/false));
-        if (mGralloc4->getAllocator() == nullptr || mGralloc4->getMapper() == nullptr) {
+        ASSERT_NO_FATAL_FAILURE(mGralloc4 = std::make_shared<Gralloc4>(
+                                        /*aidlAllocatorServiceName*/ IAllocator::descriptor +
+                                                std::string("/default"),
+                                        /*hidlAllocatorServiceName*/ "default",
+                                        /*mapperServiceName*/ "default",
+                                        /*errOnFailure=*/false));
+        if (!mGralloc4->hasAllocator() || mGralloc4->getMapper() == nullptr) {
             mGralloc4 = nullptr;
             ASSERT_NO_FATAL_FAILURE(mGralloc3 = std::make_shared<Gralloc3>("default", "default",
                                                                            /*errOnFailure=*/false));
diff --git a/graphics/composer/2.1/utils/vts/include/composer-vts/2.1/ComposerVts.h b/graphics/composer/2.1/utils/vts/include/composer-vts/2.1/ComposerVts.h
index 2949823..f8ea661 100644
--- a/graphics/composer/2.1/utils/vts/include/composer-vts/2.1/ComposerVts.h
+++ b/graphics/composer/2.1/utils/vts/include/composer-vts/2.1/ComposerVts.h
@@ -49,6 +49,7 @@
 using Gralloc2 = android::hardware::graphics::mapper::V2_0::vts::Gralloc;
 using Gralloc3 = android::hardware::graphics::mapper::V3_0::vts::Gralloc;
 using Gralloc4 = android::hardware::graphics::mapper::V4_0::vts::Gralloc;
+using IAllocator = aidl::android::hardware::graphics::allocator::IAllocator;
 
 class ComposerClient;
 
diff --git a/graphics/composer/2.1/vts/functional/Android.bp b/graphics/composer/2.1/vts/functional/Android.bp
index 9ffd7d5..502036e 100644
--- a/graphics/composer/2.1/vts/functional/Android.bp
+++ b/graphics/composer/2.1/vts/functional/Android.bp
@@ -32,14 +32,17 @@
     // TODO(b/64437680): Assume these libs are always available on the device.
     shared_libs: [
         "libbase",
+        "libbinder_ndk",
         "libfmq",
         "libsync",
+        "android.hardware.common-V2-ndk",
         "android.hardware.graphics.mapper@2.0",
         "android.hardware.graphics.mapper@2.1",
         "android.hardware.graphics.mapper@3.0",
         "android.hardware.graphics.mapper@4.0",
     ],
     static_libs: [
+        "android.hardware.graphics.allocator-V1-ndk",
         "android.hardware.graphics.allocator@2.0",
         "android.hardware.graphics.allocator@3.0",
         "android.hardware.graphics.allocator@4.0",
@@ -49,10 +52,14 @@
         "android.hardware.graphics.mapper@2.1-vts",
         "android.hardware.graphics.mapper@3.0-vts",
         "android.hardware.graphics.mapper@4.0-vts",
+        "libaidlcommonsupport",
     ],
     header_libs: [
         "android.hardware.graphics.composer@2.1-command-buffer",
     ],
     disable_framework: true,
-    test_suites: ["general-tests", "vts"],
+    test_suites: [
+        "general-tests",
+        "vts",
+    ],
 }
diff --git a/graphics/composer/2.2/utils/vts/Android.bp b/graphics/composer/2.2/utils/vts/Android.bp
index aa8e541..cca5323 100644
--- a/graphics/composer/2.2/utils/vts/Android.bp
+++ b/graphics/composer/2.2/utils/vts/Android.bp
@@ -35,6 +35,7 @@
         "libui",
     ],
     static_libs: [
+        "android.hardware.graphics.allocator-V1-ndk",
         "android.hardware.graphics.composer@2.1-vts",
         "android.hardware.graphics.composer@2.2",
         "android.hardware.graphics.composer3-V1-ndk",
@@ -52,6 +53,7 @@
         "android.hardware.graphics.mapper@4.0-vts",
     ],
     export_static_lib_headers: [
+        "android.hardware.graphics.allocator-V1-ndk",
         "android.hardware.graphics.composer@2.1-vts",
         "android.hardware.graphics.composer@2.2",
         "android.hardware.graphics.mapper@2.1-vts",
diff --git a/graphics/composer/2.2/utils/vts/ComposerVts.cpp b/graphics/composer/2.2/utils/vts/ComposerVts.cpp
index a526137..b706596 100644
--- a/graphics/composer/2.2/utils/vts/ComposerVts.cpp
+++ b/graphics/composer/2.2/utils/vts/ComposerVts.cpp
@@ -182,9 +182,13 @@
 Gralloc::Gralloc() {
     [this] {
         ALOGD("Attempting to initialize gralloc4");
-        ASSERT_NO_FATAL_FAILURE(mGralloc4 = std::make_shared<Gralloc4>("default", "default",
-                                                                       /*errOnFailure=*/false));
-        if (mGralloc4->getMapper() == nullptr || mGralloc4->getAllocator() == nullptr) {
+        ASSERT_NO_FATAL_FAILURE(mGralloc4 = std::make_shared<Gralloc4>(
+                                        /*aidlAllocatorServiceName*/ IAllocator::descriptor +
+                                                std::string("/default"),
+                                        /*hidlAllocatorServiceName*/ "default",
+                                        /*mapperServiceName*/ "default",
+                                        /*errOnFailure=*/false));
+        if (mGralloc4->getMapper() == nullptr || !mGralloc4->hasAllocator()) {
             mGralloc4 = nullptr;
             ALOGD("Failed to initialize gralloc4, initializing gralloc3");
             ASSERT_NO_FATAL_FAILURE(mGralloc3 = std::make_shared<Gralloc3>("default", "default",
diff --git a/graphics/composer/2.2/utils/vts/include/composer-vts/2.2/ComposerVts.h b/graphics/composer/2.2/utils/vts/include/composer-vts/2.2/ComposerVts.h
index d3bba17..02d7bdb 100644
--- a/graphics/composer/2.2/utils/vts/include/composer-vts/2.2/ComposerVts.h
+++ b/graphics/composer/2.2/utils/vts/include/composer-vts/2.2/ComposerVts.h
@@ -48,6 +48,7 @@
 using Gralloc2_1 = android::hardware::graphics::mapper::V2_1::vts::Gralloc;
 using Gralloc3 = android::hardware::graphics::mapper::V3_0::vts::Gralloc;
 using Gralloc4 = android::hardware::graphics::mapper::V4_0::vts::Gralloc;
+using IAllocator = aidl::android::hardware::graphics::allocator::IAllocator;
 
 class ComposerClient;
 
diff --git a/graphics/composer/2.2/vts/functional/Android.bp b/graphics/composer/2.2/vts/functional/Android.bp
index dd519e7..960b62d 100644
--- a/graphics/composer/2.2/vts/functional/Android.bp
+++ b/graphics/composer/2.2/vts/functional/Android.bp
@@ -45,18 +45,21 @@
         "libGLESv1_CM",
         "libGLESv2",
         "libbase",
+        "libbinder_ndk",
         "libfmq",
         "libgui",
         "libhidlbase",
         "libprocessgroup",
         "libsync",
         "libui",
+        "android.hardware.common-V2-ndk",
         "android.hardware.graphics.mapper@2.0",
         "android.hardware.graphics.mapper@2.1",
         "android.hardware.graphics.mapper@3.0",
         "android.hardware.graphics.mapper@4.0",
     ],
     static_libs: [
+        "android.hardware.graphics.allocator-V1-ndk",
         "android.hardware.graphics.allocator@2.0",
         "android.hardware.graphics.allocator@3.0",
         "android.hardware.graphics.allocator@4.0",
@@ -70,6 +73,7 @@
         "android.hardware.graphics.mapper@2.1-vts",
         "android.hardware.graphics.mapper@3.0-vts",
         "android.hardware.graphics.mapper@4.0-vts",
+        "libaidlcommonsupport",
         "libgtest",
         "librenderengine",
         "libshaders",
diff --git a/graphics/composer/2.3/vts/functional/Android.bp b/graphics/composer/2.3/vts/functional/Android.bp
index 70384ac..40b77d5 100644
--- a/graphics/composer/2.3/vts/functional/Android.bp
+++ b/graphics/composer/2.3/vts/functional/Android.bp
@@ -32,15 +32,18 @@
     // TODO(b/64437680): Assume these libs are always available on the device.
     shared_libs: [
         "libbase",
+        "libbinder_ndk",
         "libfmq",
         "libhidlbase",
         "libsync",
+        "android.hardware.common-V2-ndk",
         "android.hardware.graphics.mapper@2.0",
         "android.hardware.graphics.mapper@2.1",
         "android.hardware.graphics.mapper@3.0",
         "android.hardware.graphics.mapper@4.0",
     ],
     static_libs: [
+        "android.hardware.graphics.allocator-V1-ndk",
         "android.hardware.graphics.allocator@2.0",
         "android.hardware.graphics.allocator@3.0",
         "android.hardware.graphics.allocator@4.0",
@@ -54,6 +57,7 @@
         "android.hardware.graphics.mapper@2.1-vts",
         "android.hardware.graphics.mapper@3.0-vts",
         "android.hardware.graphics.mapper@4.0-vts",
+        "libaidlcommonsupport",
     ],
     header_libs: [
         "android.hardware.graphics.composer@2.1-command-buffer",
@@ -61,5 +65,8 @@
         "android.hardware.graphics.composer@2.3-command-buffer",
     ],
     disable_framework: true,
-    test_suites: ["general-tests", "vts"],
+    test_suites: [
+        "general-tests",
+        "vts",
+    ],
 }
diff --git a/graphics/composer/2.4/utils/vts/Android.bp b/graphics/composer/2.4/utils/vts/Android.bp
index 5ef861c..de31975 100644
--- a/graphics/composer/2.4/utils/vts/Android.bp
+++ b/graphics/composer/2.4/utils/vts/Android.bp
@@ -32,6 +32,7 @@
         "TestCommandReader.cpp",
     ],
     static_libs: [
+        "android.hardware.graphics.allocator-V1-ndk",
         "android.hardware.graphics.composer@2.1",
         "android.hardware.graphics.composer@2.2",
         "android.hardware.graphics.composer@2.3-vts",
diff --git a/graphics/composer/2.4/vts/functional/Android.bp b/graphics/composer/2.4/vts/functional/Android.bp
index 22ae7c4..b73ea94 100644
--- a/graphics/composer/2.4/vts/functional/Android.bp
+++ b/graphics/composer/2.4/vts/functional/Android.bp
@@ -32,14 +32,17 @@
     // TODO(b/64437680): Assume these libs are always available on the device.
     shared_libs: [
         "libbase",
+        "libbinder_ndk",
         "libfmq",
         "libsync",
+        "android.hardware.common-V2-ndk",
         "android.hardware.graphics.mapper@2.0",
         "android.hardware.graphics.mapper@2.1",
         "android.hardware.graphics.mapper@3.0",
         "android.hardware.graphics.mapper@4.0",
     ],
     static_libs: [
+        "android.hardware.graphics.allocator-V1-ndk",
         "android.hardware.graphics.allocator@2.0",
         "android.hardware.graphics.allocator@3.0",
         "android.hardware.graphics.allocator@4.0",
@@ -55,6 +58,7 @@
         "android.hardware.graphics.mapper@2.1-vts",
         "android.hardware.graphics.mapper@3.0-vts",
         "android.hardware.graphics.mapper@4.0-vts",
+        "libaidlcommonsupport",
     ],
     header_libs: [
         "android.hardware.graphics.composer@2.1-command-buffer",
@@ -63,5 +67,8 @@
         "android.hardware.graphics.composer@2.4-command-buffer",
     ],
     disable_framework: true,
-    test_suites: ["general-tests", "vts"],
+    test_suites: [
+        "general-tests",
+        "vts",
+    ],
 }
diff --git a/graphics/composer/aidl/vts/VtsHalGraphicsComposer3_TargetTest.cpp b/graphics/composer/aidl/vts/VtsHalGraphicsComposer3_TargetTest.cpp
index 759bfec..047109e 100644
--- a/graphics/composer/aidl/vts/VtsHalGraphicsComposer3_TargetTest.cpp
+++ b/graphics/composer/aidl/vts/VtsHalGraphicsComposer3_TargetTest.cpp
@@ -1719,10 +1719,10 @@
             }
         }
 
+        configureLayer(display, layer, Composition::DISPLAY_DECORATION, display.getFrameRect(),
+                          display.getCrop());
         mWriter.setLayerBuffer(display.getDisplayId(), layer, /*slot*/ 0, decorBuffer->handle,
                                /*acquireFence*/ -1);
-        mWriter.setLayerCompositionType(display.getDisplayId(), layer,
-                                        Composition::DISPLAY_DECORATION);
         mWriter.validateDisplay(display.getDisplayId(), ComposerClientWriter::kNoTimestamp);
         execute();
         if (support) {
diff --git a/graphics/mapper/4.0/utils/vts/Android.bp b/graphics/mapper/4.0/utils/vts/Android.bp
index 6331498..7abf5db 100644
--- a/graphics/mapper/4.0/utils/vts/Android.bp
+++ b/graphics/mapper/4.0/utils/vts/Android.bp
@@ -32,14 +32,21 @@
         "-g",
     ],
     static_libs: [
+        "android.hardware.graphics.allocator-V1-ndk",
         "android.hardware.graphics.allocator@4.0",
+        "android.hardware.graphics.common-V3-ndk",
         "android.hardware.graphics.mapper@4.0",
+        "libaidlcommonsupport",
     ],
     shared_libs: [
+        "libbinder_ndk",
         "libgralloctypes",
+        "libvndksupport",
     ],
     export_static_lib_headers: [
+        "android.hardware.graphics.allocator-V1-ndk",
         "android.hardware.graphics.allocator@4.0",
+        "android.hardware.graphics.common-V3-ndk",
         "android.hardware.graphics.mapper@4.0",
     ],
     export_include_dirs: ["include"],
diff --git a/graphics/mapper/4.0/utils/vts/MapperVts.cpp b/graphics/mapper/4.0/utils/vts/MapperVts.cpp
index 4a6f68d..c6c9834 100644
--- a/graphics/mapper/4.0/utils/vts/MapperVts.cpp
+++ b/graphics/mapper/4.0/utils/vts/MapperVts.cpp
@@ -14,7 +14,9 @@
  * limitations under the License.
  */
 
+#include <aidlcommonsupport/NativeHandle.h>
 #include <android-base/properties.h>
+#include <android/binder_manager.h>
 #include <gralloctypes/Gralloc4.h>
 #include <mapper-vts/4.0/MapperVts.h>
 
@@ -25,27 +27,42 @@
 namespace V4_0 {
 namespace vts {
 
-Gralloc::Gralloc(const std::string& allocatorServiceName, const std::string& mapperServiceName,
+Gralloc::Gralloc(const std::string& aidlAllocatorServiceName,
+                 const std::string& hidlAllocatorServiceName, const std::string& mapperServiceName,
                  bool errOnFailure) {
     if (errOnFailure) {
-        init(allocatorServiceName, mapperServiceName);
+        init(aidlAllocatorServiceName, hidlAllocatorServiceName, mapperServiceName);
     } else {
-        initNoErr(allocatorServiceName, mapperServiceName);
+        initNoErr(aidlAllocatorServiceName, hidlAllocatorServiceName, mapperServiceName);
     }
 }
 
-void Gralloc::init(const std::string& allocatorServiceName, const std::string& mapperServiceName) {
-    mAllocator = IAllocator::getService(allocatorServiceName);
-    ASSERT_NE(nullptr, mAllocator.get()) << "failed to get allocator service";
+void Gralloc::init(const std::string& aidlAllocatorServiceName,
+                   const std::string& hidlAllocatorServiceName,
+                   const std::string& mapperServiceName) {
+    mAidlAllocator = aidl::android::hardware::graphics::allocator::IAllocator::fromBinder(
+            ndk::SpAIBinder(AServiceManager_checkService(aidlAllocatorServiceName.c_str())));
+
+    if (mAidlAllocator == nullptr) {
+        mHidlAllocator = IAllocator::getService(hidlAllocatorServiceName);
+    }
+    ASSERT_TRUE(nullptr != mAidlAllocator || mHidlAllocator != nullptr)
+            << "failed to get allocator service";
 
     mMapper = IMapper::getService(mapperServiceName);
     ASSERT_NE(nullptr, mMapper.get()) << "failed to get mapper service";
     ASSERT_FALSE(mMapper->isRemote()) << "mapper is not in passthrough mode";
 }
 
-void Gralloc::initNoErr(const std::string& allocatorServiceName,
+void Gralloc::initNoErr(const std::string& aidlAllocatorServiceName,
+                        const std::string& hidlAllocatorServiceName,
                         const std::string& mapperServiceName) {
-    mAllocator = IAllocator::getService(allocatorServiceName);
+    mAidlAllocator = aidl::android::hardware::graphics::allocator::IAllocator::fromBinder(
+            ndk::SpAIBinder(AServiceManager_checkService(aidlAllocatorServiceName.c_str())));
+
+    if (mAidlAllocator == nullptr) {
+        mHidlAllocator = IAllocator::getService(hidlAllocatorServiceName);
+    }
 
     mMapper = IMapper::getService(mapperServiceName);
     if (mMapper.get()) {
@@ -68,10 +85,6 @@
     mImportedBuffers.clear();
 }
 
-sp<IAllocator> Gralloc::getAllocator() const {
-    return mAllocator;
-}
-
 const native_handle_t* Gralloc::cloneBuffer(const hidl_handle& rawHandle,
                                             enum Tolerance /*tolerance*/) {
     const native_handle_t* bufferHandle = native_handle_clone(rawHandle.getNativeHandle());
@@ -90,40 +103,40 @@
                                                       uint32_t* outStride) {
     std::vector<const native_handle_t*> bufferHandles;
     bufferHandles.reserve(count);
-    mAllocator->allocate(descriptor, count,
-                         [&](const auto& tmpError, const auto& tmpStride, const auto& tmpBuffers) {
-                             if (canTolerate(tolerance, tmpError)) {
-                                 return;
-                             }
 
-                             if (tmpError != Error::NONE) {
-                                 if (base::GetIntProperty("ro.vendor.build.version.sdk", 0, 0,
-                                                          INT_MAX) < 33) {
-                                     GTEST_SKIP() << "Old vendor grallocs may not support P010";
-                                 } else {
-                                     GTEST_FAIL() << "failed to allocate buffers";
-                                 }
-                             }
-                             ASSERT_EQ(count, tmpBuffers.size()) << "invalid buffer array";
+    auto callback = [&](Error error, uint32_t stride,
+                        const hidl_vec<hidl_handle>& buffers) -> void {
+        if (canTolerate(tolerance, error)) {
+            return;
+        }
 
-                             for (uint32_t i = 0; i < count; i++) {
-                                 const native_handle_t* bufferHandle = nullptr;
-                                 if (import) {
-                                     ASSERT_NO_FATAL_FAILURE(
-                                             bufferHandle = importBuffer(tmpBuffers[i], tolerance));
-                                 } else {
-                                     ASSERT_NO_FATAL_FAILURE(
-                                             bufferHandle = cloneBuffer(tmpBuffers[i], tolerance));
-                                 }
-                                 if (bufferHandle) {
-                                     bufferHandles.push_back(bufferHandle);
-                                 }
-                             }
+        if (error != Error::NONE) {
+            if (base::GetIntProperty("ro.vendor.build.version.sdk", 0, 0, INT_MAX) < 33) {
+                GTEST_SKIP() << "Old vendor grallocs may not support P010";
+            } else {
+                GTEST_FAIL() << "failed to allocate buffers";
+            }
+        }
+        ASSERT_EQ(count, buffers.size()) << "invalid buffer array";
 
-                             if (outStride) {
-                                 *outStride = tmpStride;
-                             }
-                         });
+        for (uint32_t i = 0; i < count; i++) {
+            const native_handle_t* bufferHandle = nullptr;
+            if (import) {
+                ASSERT_NO_FATAL_FAILURE(bufferHandle = importBuffer(buffers[i], tolerance));
+            } else {
+                ASSERT_NO_FATAL_FAILURE(bufferHandle = cloneBuffer(buffers[i], tolerance));
+            }
+            if (bufferHandle) {
+                bufferHandles.push_back(bufferHandle);
+            }
+        }
+
+        if (outStride) {
+            *outStride = stride;
+        }
+    };
+
+    rawAllocate(descriptor, count, callback);
 
     if (::testing::Test::HasFatalFailure()) {
         bufferHandles.clear();
@@ -147,6 +160,23 @@
     return buffers[0];
 }
 
+void Gralloc::rawAllocate(
+        const BufferDescriptor& descriptor, uint32_t count,
+        std::function<void(Error, uint32_t, const hidl_vec<hidl_handle>&)> callback) {
+    if (mAidlAllocator) {
+        aidl::android::hardware::graphics::allocator::AllocationResult result;
+        auto status = mAidlAllocator->allocate(descriptor, count, &result);
+        const Error error = toHidlError(status);
+        std::vector<hidl_handle> handles;
+        for (const auto& aidlHandle : result.buffers) {
+            handles.push_back(hidl_handle(makeFromAidl(aidlHandle)));
+        }
+        callback(error, result.stride, handles);
+    } else {
+        mHidlAllocator->allocate(descriptor, count, callback);
+    }
+}
+
 sp<IMapper> Gralloc::getMapper() const {
     return mMapper;
 }
diff --git a/graphics/mapper/4.0/utils/vts/include/mapper-vts/4.0/MapperVts.h b/graphics/mapper/4.0/utils/vts/include/mapper-vts/4.0/MapperVts.h
index c5406c9..ecbbc58 100644
--- a/graphics/mapper/4.0/utils/vts/include/mapper-vts/4.0/MapperVts.h
+++ b/graphics/mapper/4.0/utils/vts/include/mapper-vts/4.0/MapperVts.h
@@ -20,6 +20,8 @@
 #include <unordered_set>
 #include <vector>
 
+#include <aidl/android/hardware/graphics/allocator/AllocationError.h>
+#include <aidl/android/hardware/graphics/allocator/IAllocator.h>
 #include <android/hardware/graphics/allocator/4.0/IAllocator.h>
 #include <android/hardware/graphics/mapper/4.0/IMapper.h>
 #include <gtest/gtest.h>
@@ -47,13 +49,39 @@
         kToleranceAllErrors = ~0x0U,
     };
 
-    Gralloc(const std::string& allocatorServiceName = "default",
+    Gralloc(const std::string& aidlAllocatorServiceName =
+                    "android.hardware.graphics.allocator.IAllocator/default",
+            const std::string& hidlAllocatorServiceName = "default",
             const std::string& mapperServiceName = "default", bool errOnFailure = true);
     ~Gralloc();
 
+    static Error toHidlError(aidl::android::hardware::graphics::allocator::AllocationError error) {
+        switch (error) {
+            case aidl::android::hardware::graphics::allocator::AllocationError::BAD_DESCRIPTOR:
+                return Error::BAD_DESCRIPTOR;
+            case aidl::android::hardware::graphics::allocator::AllocationError::NO_RESOURCES:
+                return Error::NO_RESOURCES;
+            case aidl::android::hardware::graphics::allocator::AllocationError::UNSUPPORTED:
+                return Error::UNSUPPORTED;
+        }
+    }
+    static Error toHidlError(const ndk::ScopedAStatus& status) {
+        if (status.isOk()) {
+            return Error::NONE;
+        }
+
+        if (status.getExceptionCode() != EX_SERVICE_SPECIFIC) {
+            return Error::NO_RESOURCES;
+        }
+
+        return toHidlError(
+                static_cast<aidl::android::hardware::graphics::allocator::AllocationError>(
+                        status.getServiceSpecificError()));
+    }
+
     // IAllocator methods
 
-    sp<IAllocator> getAllocator() const;
+    bool hasAllocator() { return mHidlAllocator != nullptr || mAidlAllocator != nullptr; }
 
     // When import is false, this simply calls IAllocator::allocate. When import
     // is true, the returned buffers are also imported into the mapper.
@@ -81,6 +109,10 @@
         return allocate(descriptorInfo, import, Tolerance::kToleranceStrict, outStride);
     }
 
+    // Dispatches directly to the allocator
+    void rawAllocate(const BufferDescriptor& descriptor, uint32_t count,
+                     std::function<void(Error, uint32_t, const hidl_vec<hidl_handle>&)> callback);
+
     // IMapper methods
 
     sp<IMapper> getMapper() const;
@@ -134,16 +166,20 @@
                 0x1U << std::underlying_type_t<Error>(error)) != 0;
     }
 
-    void init(const std::string& allocatorServiceName, const std::string& mapperServiceName);
+    void init(const std::string& aidlAllocatorServiceName,
+              const std::string& hidlAllocatorServiceName, const std::string& mapperServiceName);
 
     // initialize without checking for failure to get service
-    void initNoErr(const std::string& allocatorServiceName, const std::string& mapperServiceName);
+    void initNoErr(const std::string& aidlAllocatorServiceName,
+                   const std::string& hidlAllocatorServiceName,
+                   const std::string& mapperServiceName);
     const native_handle_t* cloneBuffer(const hidl_handle& rawHandle, enum Tolerance tolerance);
     const native_handle_t* cloneBuffer(const hidl_handle& rawHandle) {
         return cloneBuffer(rawHandle, Tolerance::kToleranceStrict);
     }
 
-    sp<IAllocator> mAllocator;
+    sp<IAllocator> mHidlAllocator;
+    std::shared_ptr<aidl::android::hardware::graphics::allocator::IAllocator> mAidlAllocator;
     sp<IMapper> mMapper;
 
     // Keep track of all cloned and imported handles.  When a test fails with
diff --git a/graphics/mapper/4.0/vts/functional/Android.bp b/graphics/mapper/4.0/vts/functional/Android.bp
index 65bc380..e830633 100644
--- a/graphics/mapper/4.0/vts/functional/Android.bp
+++ b/graphics/mapper/4.0/vts/functional/Android.bp
@@ -25,20 +25,27 @@
 
 cc_test {
     name: "VtsHalGraphicsMapperV4_0TargetTest",
-    defaults: ["VtsHalTargetTestDefaults"],
+    defaults: [
+        "VtsHalTargetTestDefaults",
+        "use_libaidlvintf_gtest_helper_static",
+    ],
     srcs: ["VtsHalGraphicsMapperV4_0TargetTest.cpp"],
     static_libs: [
         "android.hardware.graphics.common-V3-ndk",
         "android.hardware.graphics.mapper@4.0-vts",
+        "libaidlcommonsupport",
         "libgralloctypes",
         "libsync",
     ],
     shared_libs: [
+        "android.hardware.graphics.allocator-V1-ndk",
         "android.hardware.graphics.allocator@4.0",
         "android.hardware.graphics.common@1.0",
         "android.hardware.graphics.common@1.1",
         "android.hardware.graphics.common@1.2",
         "android.hardware.graphics.mapper@4.0",
+        "libbinder_ndk",
+        "libvndksupport",
     ],
     header_libs: [
         "libsystem_headers",
diff --git a/graphics/mapper/4.0/vts/functional/VtsHalGraphicsMapperV4_0TargetTest.cpp b/graphics/mapper/4.0/vts/functional/VtsHalGraphicsMapperV4_0TargetTest.cpp
index 2aac337..5a450e3 100644
--- a/graphics/mapper/4.0/vts/functional/VtsHalGraphicsMapperV4_0TargetTest.cpp
+++ b/graphics/mapper/4.0/vts/functional/VtsHalGraphicsMapperV4_0TargetTest.cpp
@@ -21,8 +21,12 @@
 #include <thread>
 #include <vector>
 
+#include <aidl/Vintf.h>
+#include <aidl/android/hardware/graphics/allocator/AllocationError.h>
+#include <aidl/android/hardware/graphics/allocator/AllocationResult.h>
 #include <aidl/android/hardware/graphics/common/PixelFormat.h>
 #include <aidl/android/hardware/graphics/common/PlaneLayoutComponentType.h>
+#include <aidlcommonsupport/NativeHandle.h>
 
 #include <android-base/logging.h>
 #include <android-base/unique_fd.h>
@@ -72,7 +76,7 @@
     void SetUp() override {
         ASSERT_NO_FATAL_FAILURE(mGralloc = std::make_unique<Gralloc>(std::get<0>(GetParam()),
                                                                      std::get<1>(GetParam())));
-        ASSERT_NE(nullptr, mGralloc->getAllocator().get());
+        ASSERT_TRUE(mGralloc->hasAllocator());
         ASSERT_NE(nullptr, mGralloc->getMapper().get());
 
         mDummyDescriptorInfo.name = "dummy";
@@ -504,10 +508,10 @@
 TEST_P(GraphicsMapperHidlTest, AllocatorAllocateNegative) {
     // this assumes any valid descriptor is non-empty
     BufferDescriptor descriptor;
-    mGralloc->getAllocator()->allocate(descriptor, 1,
-                                       [&](const auto& tmpError, const auto&, const auto&) {
-                                           EXPECT_EQ(Error::BAD_DESCRIPTOR, tmpError);
-                                       });
+
+    mGralloc->rawAllocate(descriptor, 1, [&](const auto& tmpError, const auto&, const auto&) {
+        EXPECT_EQ(Error::BAD_DESCRIPTOR, tmpError);
+    });
 }
 
 /**
@@ -535,9 +539,9 @@
     std::atomic<uint64_t> allocationCount(0);
     auto threadLoop = [&]() {
         while (!timeUp) {
-            mGralloc->getAllocator()->allocate(
-                    descriptor, 1,
-                    [&](const auto&, const auto&, const auto&) { allocationCount++; });
+            mGralloc->rawAllocate(descriptor, 1, [&](const auto&, const auto&, const auto&) {
+                allocationCount++;
+            });
         }
     };
 
@@ -2755,8 +2759,9 @@
         BufferDescriptor descriptor;
         ASSERT_NO_FATAL_FAILURE(descriptor = mGralloc->createDescriptor(info));
 
-        Error err;
-        mGralloc->getAllocator()->allocate(
+        Error err = Error::NONE;
+
+        mGralloc->rawAllocate(
                 descriptor, 1, [&](const auto& tmpError, const auto&, const auto& tmpBuffers) {
                     err = tmpError;
                     if (err == Error::NONE) {
@@ -2827,11 +2832,27 @@
 }
 
 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(GraphicsMapperHidlTest);
+
+namespace {
+std::vector<std::string> getAllocatorInstances() {
+    std::vector<std::string> instances;
+    for (auto halInstance : android::hardware::getAllHalInstanceNames(IAllocator::descriptor)) {
+        instances.emplace_back(std::move(halInstance));
+    }
+
+    for (auto aidlInstance : getAidlHalInstanceNames(
+                 aidl::android::hardware::graphics::allocator::IAllocator::descriptor)) {
+        instances.emplace_back(std::move(aidlInstance));
+    }
+
+    return instances;
+}
+}  // namespace
+
 INSTANTIATE_TEST_CASE_P(
         PerInstance, GraphicsMapperHidlTest,
         testing::Combine(
-                testing::ValuesIn(
-                        android::hardware::getAllHalInstanceNames(IAllocator::descriptor)),
+                testing::ValuesIn(getAllocatorInstances()),
                 testing::ValuesIn(android::hardware::getAllHalInstanceNames(IMapper::descriptor))),
         android::hardware::PrintInstanceTupleNameToString<>);
 
diff --git a/keymaster/4.0/vts/functional/keymaster_hidl_hal_test.cpp b/keymaster/4.0/vts/functional/keymaster_hidl_hal_test.cpp
index bf56860..fb5048a 100644
--- a/keymaster/4.0/vts/functional/keymaster_hidl_hal_test.cpp
+++ b/keymaster/4.0/vts/functional/keymaster_hidl_hal_test.cpp
@@ -27,6 +27,7 @@
 #include <openssl/mem.h>
 #include <openssl/x509.h>
 
+#include <android-base/properties.h>
 #include <cutils/properties.h>
 
 #include <keymasterV4_0/attestation_record.h>
@@ -386,6 +387,31 @@
     return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
 }
 
+int get_vsr_api_level() {
+    int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
+    if (vendor_api_level != -1) {
+        return vendor_api_level;
+    }
+
+    // Android S and older devices do not define ro.vendor.api_level
+    vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1);
+    if (vendor_api_level == -1) {
+        vendor_api_level = ::android::base::GetIntProperty("ro.board.first_api_level", -1);
+    }
+
+    int product_api_level = ::android::base::GetIntProperty("ro.product.first_api_level", -1);
+    if (product_api_level == -1) {
+        product_api_level = ::android::base::GetIntProperty("ro.build.version.sdk", -1);
+        EXPECT_NE(product_api_level, -1) << "Could not find ro.build.version.sdk";
+    }
+
+    // VSR API level is the minimum of vendor_api_level and product_api_level.
+    if (vendor_api_level == -1 || vendor_api_level > product_api_level) {
+        return product_api_level;
+    }
+    return vendor_api_level;
+}
+
 bool is_gsi() {
     char property_value[PROPERTY_VALUE_MAX] = {};
     EXPECT_NE(property_get("ro.product.system.name", property_value, ""), 0);
@@ -4833,6 +4859,18 @@
 
 INSTANTIATE_KEYMASTER_HIDL_TEST(TransportLimitTest);
 
+using VsrRequirementTest = KeymasterHidlTest;
+
+TEST_P(VsrRequirementTest, Vsr13Test) {
+    int vsr_api_level = get_vsr_api_level();
+    if (vsr_api_level < 33) {
+        GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
+    }
+    FAIL() << "VSR 13+ requires KeyMint version 2";
+}
+
+INSTANTIATE_KEYMASTER_HIDL_TEST(VsrRequirementTest);
+
 }  // namespace test
 }  // namespace V4_0
 }  // namespace keymaster
diff --git a/media/omx/1.0/vts/functional/store/VtsHalMediaOmxV1_0TargetStoreTest.cpp b/media/omx/1.0/vts/functional/store/VtsHalMediaOmxV1_0TargetStoreTest.cpp
index 2ae9c2b..00e9837 100755
--- a/media/omx/1.0/vts/functional/store/VtsHalMediaOmxV1_0TargetStoreTest.cpp
+++ b/media/omx/1.0/vts/functional/store/VtsHalMediaOmxV1_0TargetStoreTest.cpp
@@ -400,9 +400,18 @@
                             << " Component: " << info.mName.c_str() << " Role: " << role.c_str()
                             << " not allowed for devices launching with Android T and above";
                 } else {
-                    ASSERT_LT(getFirstApiLevel(), __ANDROID_API_S__)
+                    std::string codecName = info.mName;
+                    bool isAndroidCodec = (codecName.rfind("OMX.google", 0) != std::string::npos);
+                    if (isAndroidCodec && (getFirstApiLevel() <= __ANDROID_API_S__)) {
+                        // refer b/230582620
+                        // S AOSP build did not remove the OMX.google video codecs
+                        // so it is infeasible to require no OMX.google.* video codecs
+                        // on S launching devices
+                    } else {
+                        ASSERT_LT(getFirstApiLevel(), __ANDROID_API_S__)
                             << " Component: " << info.mName.c_str() << " Role: " << role.c_str()
                             << " not allowed for devices launching with Android S and above";
+                    }
                 }
             }
             if (role.find("audio_decoder") != std::string::npos ||
diff --git a/power/aidl/vts/VtsHalPowerTargetTest.cpp b/power/aidl/vts/VtsHalPowerTargetTest.cpp
index e0ca87f..2cfa04a 100644
--- a/power/aidl/vts/VtsHalPowerTargetTest.cpp
+++ b/power/aidl/vts/VtsHalPowerTargetTest.cpp
@@ -211,19 +211,6 @@
     }
 }
 
-// GAME_LOADING mode is required for all devices which ship on Android T
-// or later
-TEST_P(PowerAidl, hasGameLoading) {
-    auto apiLevel = GetUintProperty<uint64_t>("ro.vendor.api_level", 0);
-    ASSERT_NE(apiLevel, 0);
-
-    if (apiLevel >= 33) {
-        bool supported;
-        ASSERT_TRUE(power->isModeSupported(Mode::GAME_LOADING, &supported).isOk());
-        ASSERT_TRUE(supported);
-    }
-}
-
 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(PowerAidl);
 INSTANTIATE_TEST_SUITE_P(Power, PowerAidl,
                          testing::ValuesIn(::android::getAidlHalInstanceNames(IPower::descriptor)),
diff --git a/security/keymint/RKP_README.md b/security/keymint/RKP_README.md
new file mode 100644
index 0000000..89a2598
--- /dev/null
+++ b/security/keymint/RKP_README.md
@@ -0,0 +1,374 @@
+# Remote Provisioning HAL
+
+## Objective
+
+Design a HAL to support over-the-air provisioning of certificates for asymmetric
+keys. The HAL must interact effectively with Keystore (and other daemons) and
+protect device privacy and security.
+
+Note that this API is designed for KeyMint, but with the intention that it
+should be usable for other HALs that require certificate provisioning.
+Throughout this document we'll refer to the Keystore and KeyMint (formerly
+called Keymaster) components, but only for concreteness and convenience; those
+labels could be replaced with the names of any system and secure area
+components, respectively, that need certificates provisioned.
+
+## Key design decisions
+
+### General approach
+
+To more securely and reliably get keys and certificates to Android devices, we
+need to create a system where no party outside of the device's secure components
+is responsible for managing private keys. The strategy we've chosen is to
+deliver certificates over the air, using an asymmetric key pair created
+on-device in the factory as a root of trust to create an authenticated, secure
+channel. In this document we refer to this device-unique asymmetric key pair as
+Device Key (DK), its public half DK\_pub, its private half DK\_priv and a Device
+Key Certificate containing DK\_pub is denoted DKC.
+
+In order for the provisioning service to use DK (or a key authenticated by DK),
+it must know whether a given DK\_pub is known and trusted. To prove trust, we
+ask device OEMs to use one of two mechanisms:
+
+1.  (Preferred, recommended) The device OEM extracts DK\_pub from each device it
+    manufactures and uploads the public keys to a backend server.
+
+1.  The device OEM signs the DK\_pub to produce DKC and stores it on the device.
+    This has the advantage that they don't need to upload a DK\_pub for every
+    device immediately, but the disadvantage that they have to manage their
+    private signing keys, which means they have to have HSMs, configure and
+    secure them correctly, etc. Some backend providers may also require that the
+    OEM passes a factory security audit, and additionally promises to upload the
+    keys eventually as well.
+
+Note that in the full elaboration of this plan, DK\_pub is not the key used to
+establish a secure channel. Instead, DK\_pub is just the first public key in a
+chain of public keys which ends with the KeyMint public key, KM\_pub. All keys
+in the chain are device-unique and are joined in a certificate chain called the
+_Boot Certificate Chain_ (BCC), because in phases 2 and 3 of the remote
+provisioning project it is a chain of certificates corresponding to boot phases.
+We speak of the BCC even for phase 1, though in phase 1 it contains only a
+single self-signed DKC. This is described in more depth in the Phases section
+below.
+
+The BCC is authenticated by DK\_pub. To authenticate DK\_pub, we may have
+additional DKCs, from the SoC vendor, the device OEM, or both. Those are not
+part of the BCC but included as optional fields in the certificate request
+structure.
+
+The format of the the DK and BCC is specified within [Open Profile for DICE]
+(https://pigweed.googlesource.com/open-dice/+/HEAD/docs/specification.md).  To
+map phrases within this document to their equivalent terminology in the DICE
+specification, read the terms as follows: the DK corresponds to the UDS-derived
+key pair, DKC corresponds to the UDS certificate, and the BCC entries between
+DK\_pub and KM\_pub correspond to a chain of CDI certificates.
+
+Note: In addition to allowing 32 byte hash values for fields in the BCC payload,
+this spec additionally constrains some of the choices allowed in open-DICE.
+Specifically, these include which entries are required and which are optional in
+the BCC payload, and which algorithms are acceptable for use.
+
+### Phases
+
+RKP will be deployed in three phases, in terms of managing the root of trust
+binding between the device and the backend. To briefly describe them:
+
+* Phase 1: In phase 1 there is only one entry in the BCC; DK_pub and KM_pub are
+  the same key and the certificate is self-signed.
+* Phase 2: This is identical to phase 1, except it leverages the hardware root
+  of trust process described by DICE. Instead of trust being rooted in the TEE,
+  it is now rooted in the ROM by key material blown into fuses which are only
+  accessible to the ROM code.
+* Phase 3: This is identical to Phase 2, except the SoC vendor also does the
+  public key extraction or certification in their facilities, along with the OEM
+  doing it in the factory. This tightens up the "supply chain" and aims to make
+  key upload management more secure.
+
+### Privacy considerations
+
+Because DK and the DKCs are unique, immutable, unspoofable hardware-bound
+identifiers for the device, we must limit access to them to the absolute minimum
+possible. We do this in two ways:
+
+1.  We require KeyMint (which knows the BCC and either knows or at least has the
+ability to use KM\_priv) to refuse to ever divulge the BCC or additional
+signatures in plaintext. Instead, KeyMint requires the caller to provide an
+_Endpoint Encryption Key_ (EEK), with which it will encrypt the data before
+returning it. When provisioning production keys, the EEK must be signed by an
+approved authority whose public key is embedded in KeyMint. When certifying test
+keys, KeyMint will accept any EEK without checking the signature, but will
+encrypt and return a test BCC, rather than the real one.  The result is that
+only an entity in possession of an Trusted EEK (TEEK) private key can discover
+the plaintext of the production BCC.
+1.  Having thus limited access to the public keys to the trusted party only, we
+need to prevent the entity from abusing this unique device identifier.  The
+approach and mechanisms for doing that are beyond the scope of this document
+(they must be addressed in the server design), but generally involve taking care
+to ensure that we do not create any links between user IDs, IP addresses or
+issued certificates and the device pubkey.
+
+Although the details of the mechanisms for preventing the entity from abusing
+the BCC are, as stated, beyond the scope of this document, there is a subtle
+design decision here made specifically to enable abuse prevention. Specifically
+the `CertificateRequest` message sent to the server is (in
+[CDDL](https://tools.ietf.org/html/rfc8610)):
+
+```
+cddl
+CertificateRequest = [
+    DeviceInfo,
+    challenge : bstr,
+    ProtectedData,
+    MacedKeysToSign
+]
+```
+
+The public keys to be attested by the server are in `MacedKeysToSign`, which is
+a COSE\_Mac0 structure, MACed with a key that is found in `ProtectedData`. The
+MAC key is signed by DK\_pub.
+
+This structure allows the backend component that has access to EEK\_priv to
+decrypt `ProtectedData`, validate that the request is from an authorized device,
+check that the request is fresh and verify and extract the MAC key. That backend
+component never sees any data related to the keys to be signed, but can provide
+the MAC key to another backend component that can verify `MacedKeysToSign` and
+proceed to generate the certificates.
+
+In this way, we can partition the provisioning server into one component that
+knows the device identity, as represented by DK\_pub, but never sees the keys to
+be certified or certificates generated, and another component that sees the keys
+to be certified and certificates generated but does not know the device
+identity.
+
+### Key and cryptographic message formatting
+
+For simplicity of generation and parsing, compactness of wire representation,
+and flexibility and standardization, we've settled on using the CBOR Object
+Signing and Encryption (COSE) standard, defined in [RFC
+8152](https://tools.ietf.org/html/rfc8152). COSE provides compact and reasonably
+simple, yet easily-extensible, wire formats for:
+
+*   Keys,
+*   MACed messages,
+*   Signed messages, and
+*   Encrypted messages
+
+COSE enables easy layering of these message formats, such as using a COSE\_Sign
+structure to contain a COSE\_Key with a public key in it. We call this a
+"certificate".
+
+Due to the complexity of the standard, we'll spell out the COSE structures
+completely in this document and in the HAL and other documentation, so that
+although implementors will need to understand CBOR and the CBOR Data Definition
+Language ([CDDL, defined in RFC 8610](https://tools.ietf.org/html/rfc8610)),
+they shouldn't need to understand COSE.
+
+Note, however, that the certificate chains returned from the provisioning server
+are standard X.509 certificates.
+
+### Algorithm choices
+
+This document uses:
+
+*   ECDSA P-256 for attestation signing keys;
+*   Remote provisioning protocol signing keys:
+  *  Ed25519 / P-256
+*   ECDH keys:
+  *  X25519 / P-256
+*   AES-GCM for all encryption;
+*   SHA-256 for all message digesting;
+*   HMAC-SHA-256 for all MACing; and
+*   HKDF-SHA-256 for all key derivation.
+
+We believe that Curve25519 offers the best tradeoff in terms of security,
+efficiency and global trustworthiness, and that it is now sufficiently
+widely-used and widely-implemented to make it a practical choice.
+
+However, since Secure Elements (SE) do not currently offer support for curve
+25519, we are allowing implementations to instead make use of EC P-256 for
+signing and ECDH. To put it simply, the device unique key pair will be a P-256
+key pair for ECDSA instead of Ed25519, and the ProtectedData COSE\_Encrypt
+message will have its payload encrypted with P-256 ECDH key exchange instead of
+X25519.
+
+The CDDL in the rest of the document will use the '/' operator to show areas
+where either curve 25519 or P-256 may be used. Since there is no easy way to
+bind choices across different CDDL groups, it is important that the implementor
+stays consistent in which type is chosen. E.g. taking ES256 as the choice for
+algorithm implies the implementor should also choose the P256 public key group
+further down in the COSE structure.
+
+### Testability
+
+It's critical that the remote provisioning implementation be testable, to
+minimize the probability that broken devices are sold to end users. To support
+testing, the remote provisioning HAL methods take a `testMode` argument. Keys
+created in test mode are tagged to indicate this. The provisioning server will
+check for the test mode tag and issue test certificates that do not chain back
+to a trusted public key. In test mode, any EEK will be accepted, enabling
+testing tools to use EEKs for which they have the private key so they can
+validate the content of certificate requests. The BCC included in the
+`CertificateRequest` must contain freshly-generated keys, not the real BCC keys.
+
+Keystore (or similar) will need to be able to handle both testMode keys and
+production keys and keep them distinct, generating test certificate requests
+when asked with a test EEK and production certificate requests when asked with a
+production EEK. Likewise, the interface used to instruct Keystore to create keys
+will need to be able to specify whether test or production keys are desired.
+
+## Design
+
+### Certificate provisioning flow
+
+TODO(jbires): Replace this with a `.png` containing a sequence diagram.  The
+provisioning flow looks something like this:
+
+Provisioner -> Keystore: Prepare N keys
+Keystore -> KeyMint: generateKeyPair
+KeyMint -> KeyMint: Generate  key pair
+KeyMint --> Keystore: key\_blob,pubkey
+Keystore -> Keystore: Store key\_blob,pubkey
+Provisioner -> Server: Get TEEK
+Server --> Provisioner: TEEK
+Provisioner -> Keystore: genCertReq(N, TEEK)
+Keystore -> KeyMint: genCertReq(pubkeys, TEEK)
+KeyMint -> KeyMint: Sign pubkeys & encrypt BCC
+KeyMint --> Keystore: signature, encrypted BCC
+Keystore -> Keystore: Construct cert\_request
+Keystore --> Provisioner: cert\_request
+Provisioner --> Server: cert\_request
+Server -> Server: Validate cert\_request
+Server -> Server: Generate certificates
+Server --> Provisioner: certificates
+Provisioner -> Keystore: certificates
+Keystore -> Keystore: Store certificates
+
+The actors in the above diagram are:
+
+*   **Server** is the backend certificate provisioning server. It has access to
+    the uploaded device public keys and is responsible for providing encryption
+    keys, decrypting and validating requests, and generating certificates in
+    response to requests.
+*   **Provisioner** is an application that is responsible for communicating with
+    the server and all of the system components that require key certificates
+    from the server. It also implements the policy that defines how many key
+    pairs each client should keep in their pool.
+*   **Keystore** is the [Android keystore
+    daemon](https://developer.android.com/training/articles/keystore) (or, more
+    generally, whatever system component manages communications with a
+    particular secure aread component).
+*   **KeyMint** is the secure area component that manages cryptographic keys and
+    performs attestations (or perhaps some other secure area component).
+
+### `BCC`
+
+The _Boot Certificate Chain_ (BCC) is the chain of certificates that contains
+DK\_pub as well as other often device-unique certificates. The BCC is
+represented as a COSE\_Key containing DK\_pub followed by an array of
+COSE\_Sign1 "certificates" containing public keys and optional additional
+information, ordered from root to leaf, with each certificate signing the next.
+The first certificate in the array is signed by DK\_pub, the last certificate
+has the KeyMint (or whatever) signing key's public key, KM\_pub. In phase 1
+there is only one entry; DK\_pub and KM\_pub are the same key and the
+certificate is self-signed.
+
+Each COSE\_Sign1 certificate is a CBOR Web Token (CWT) as described in [RFC
+8392](https://tools.ietf.org/html/rfc8392) with additional fields as described
+in the Open Profile for DICE. Of these additional fields, only the
+_subjectPublicKey_ and _keyUsage_ fields are expected to be present for the
+KM\_pub entry (that is, the last entry) in a BCC, but all fields required by the
+Open Profile for DICE are expected for other entries (each of which corresponds
+to a particular firmware component or boot stage). The CWT fields _iss_ and
+_sub_ identify the issuer and subject of the certificate and are consistent
+along the BCC entries; the issuer of a given entry matches the subject of the
+previous entry.
+
+The BCC is designed to be constructed using the Open Profile for DICE. In this
+case the DK key pair is derived from the UDS as described by that profile and
+all BCC entries before the leaf are CBOR CDI certificates chained from DK\_pub.
+The KM key pair is not part of the derived DICE chain. It is generated (not
+derived) by the KeyMint module, certified by the last key in the DICE chain, and
+added as the leaf BCC entry. The key usage field in this leaf certificate must
+indicate the key is not used to sign certificates. If a UDS certificate is
+available on the device it should appear in the certificate request as the leaf
+of a DKCertChain in AdditionalDKSignatures (see
+[CertificateRequest](#certificaterequest)).
+
+The Open Profile for DICE allows for an arbitrary configuration descriptor. For
+BCC entries, this configuration descriptor is a CBOR map with the following
+optional fields. If no fields are relevant, an empty map should be encoded.
+Additional implementation-specific fields may be added using key values not in
+the range \[-70000, -70999\] (these are reserved for future additions here).
+
+```
+| Name              | Key    | Value type | Meaning                           |
+| ----------------- | ------ | ---------- | ----------------------------------|
+| Component name    | -70002 | tstr       | Name of firmware component / boot |
+:                   :        :            : stage                             :
+| Component version | -70003 | int        | Version of firmware component /   |
+:                   :        :            : boot stage                        :
+| Resettable        | -70004 | null       | If present, key changes on factory|
+:                   :        :            : reset                             :
+```
+
+Please see
+[ProtectedData.aidl](https://cs.android.com/android/platform/superproject/+/master:hardware/interfaces/security/keymint/aidl/android/hardware/security/keymint/ProtectedData.aidl)
+for a full CDDL definition of the BCC.
+
+### `CertificateRequest`
+
+The full CBOR message that will be sent to the server to request certificates
+is:
+
+```cddl
+CertificateRequest = [
+    DeviceInfo,
+    challenge : bstr,       // Provided by the server
+    ProtectedData,          // See ProtectedData.aidl
+    MacedKeysToSign         // See IRemotelyProvisionedComponent.aidl
+]
+
+DeviceInfo = [
+    VerifiedDeviceInfo,     // See DeviceInfo.aidl
+    UnverifiedDeviceInfo
+]
+
+// Unverified info is anything provided by the HLOS. Subject to change out of
+// step with the HAL.
+UnverifiedDeviceInfo = {
+    ? "fingerprint" : tstr,
+}
+
+```
+
+It will be the responsibility of Keystore and the Provisioner to construct the
+`CertificateRequest`. The HAL provides a method to generate the elements that
+need to be constructed on the secure side, which are the tag field of
+`MacedKeysToSign`, `VerifiedDeviceInfo`, and the ciphertext field of
+`ProtectedData`.
+
+### HAL
+
+The remote provisioning HAL provides a simple interface that can be implemented
+by multiple secure components that require remote provisioning. It would be
+slightly simpler to extend the KeyMint API, but that approach would only serve
+the needs of KeyMint, this is more general.
+
+NOTE the data structures defined in this HAL may look a little bloated and
+complex. This is because the COSE data structures are fully spelled-out; we
+could make it much more compact by not re-specifying the standardized elements
+and instead just referencing the standard, but it seems better to fully specify
+them. If the apparent complexity seems daunting, consider what the same would
+look like if traditional ASN.1 DER-based structures from X.509 and related
+standards were used and also fully elaborated.
+
+Please see the related HAL documentation directly in the source code at the
+following links:
+
+*   [IRemotelyProvisionedComponent
+    HAL](https://cs.android.com/android/platform/superproject/+/master:hardware/interfaces/security/keymint/aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.aidl)
+*   [ProtectedData](https://cs.android.com/android/platform/superproject/+/master:hardware/interfaces/security/keymint/aidl/android/hardware/security/keymint/ProtectedData.aidl)
+*   [MacedPublicKey](https://cs.android.com/android/platform/superproject/+/master:hardware/interfaces/security/keymint/aidl/android/hardware/security/keymint/MacedPublicKey.aidl)
+*   [RpcHardwareInfo](https://cs.android.com/android/platform/superproject/+/master:hardware/interfaces/security/keymint/aidl/android/hardware/security/keymint/RpcHardwareInfo.aidl)
+*   [DeviceInfo](https://cs.android.com/android/platform/superproject/+/master:hardware/interfaces/security/keymint/aidl/android/hardware/security/keymint/DeviceInfo.aidl)
+
diff --git a/security/keymint/aidl/android/hardware/security/keymint/IKeyMintDevice.aidl b/security/keymint/aidl/android/hardware/security/keymint/IKeyMintDevice.aidl
index da02d54..95a3710 100644
--- a/security/keymint/aidl/android/hardware/security/keymint/IKeyMintDevice.aidl
+++ b/security/keymint/aidl/android/hardware/security/keymint/IKeyMintDevice.aidl
@@ -873,7 +873,7 @@
      * The returned data is an encoded COSE_Mac0 structure, denoted MacedRootOfTrust in the
      * following CDDL schema.  Note that K_mac is the shared HMAC key used for auth tokens, etc.:
      *
-     *     MacedRootOfTrust = [               ; COSE_Mac0 (untagged)
+     *     MacedRootOfTrust = #6.17 [         ; COSE_Mac0 (tagged)
      *         protected: bstr .cbor {
      *             1 : 5,                     ; Algorithm : HMAC-256
      *         },
@@ -891,7 +891,7 @@
      *         payload : bstr .cbor RootOfTrust,
      *     ]
      *
-     *     RootOfTrust = [
+     *     RootOfTrust = #6.40001 [           ; Tag 40001 indicates RoT v1.
      *         verifiedBootKey : bstr .size 32,
      *         deviceLocked : bool,
      *         verifiedBootState : &VerifiedBootState,
diff --git a/security/keymint/aidl/vts/functional/AttestKeyTest.cpp b/security/keymint/aidl/vts/functional/AttestKeyTest.cpp
index 240de35..ca517ac 100644
--- a/security/keymint/aidl/vts/functional/AttestKeyTest.cpp
+++ b/security/keymint/aidl/vts/functional/AttestKeyTest.cpp
@@ -16,6 +16,7 @@
 
 #define LOG_TAG "keymint_1_attest_key_test"
 #include <cutils/log.h>
+#include <cutils/properties.h>
 
 #include <keymint_support/key_param_output.h>
 #include <keymint_support/openssl_utils.h>
@@ -33,7 +34,33 @@
 
 }  // namespace
 
-using AttestKeyTest = KeyMintAidlTestBase;
+class AttestKeyTest : public KeyMintAidlTestBase {
+  protected:
+    ErrorCode GenerateAttestKey(const AuthorizationSet& key_desc,
+                                const optional<AttestationKey>& attest_key,
+                                vector<uint8_t>* key_blob,
+                                vector<KeyCharacteristics>* key_characteristics,
+                                vector<Certificate>* cert_chain) {
+        // The original specification for KeyMint v1 required ATTEST_KEY not be combined
+        // with any other key purpose, but the original VTS tests incorrectly did exactly that.
+        // This means that a device that launched prior to Android T (API level 33) may
+        // accept or even require KeyPurpose::SIGN too.
+        if (property_get_int32("ro.board.first_api_level", 0) < 33) {
+            AuthorizationSet key_desc_plus_sign = key_desc;
+            key_desc_plus_sign.push_back(TAG_PURPOSE, KeyPurpose::SIGN);
+
+            auto result = GenerateKey(key_desc_plus_sign, attest_key, key_blob, key_characteristics,
+                                      cert_chain);
+            if (result == ErrorCode::OK) {
+                return result;
+            }
+            // If the key generation failed, it may be because the device is (correctly)
+            // rejecting the combination of ATTEST_KEY+SIGN.  Fall through to try again with
+            // just ATTEST_KEY.
+        }
+        return GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
+    }
+};
 
 /*
  * AttestKeyTest.AllRsaSizes
@@ -49,12 +76,13 @@
         AttestationKey attest_key;
         vector<KeyCharacteristics> attest_key_characteristics;
         vector<Certificate> attest_key_cert_chain;
-        ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
-                                                     .RsaKey(size, 65537)
-                                                     .AttestKey()
-                                                     .SetDefaultValidity(),
-                                             {} /* attestation signing key */, &attest_key.keyBlob,
-                                             &attest_key_characteristics, &attest_key_cert_chain));
+        ASSERT_EQ(ErrorCode::OK,
+                  GenerateAttestKey(AuthorizationSetBuilder()
+                                            .RsaKey(size, 65537)
+                                            .AttestKey()
+                                            .SetDefaultValidity(),
+                                    {} /* attestation signing key */, &attest_key.keyBlob,
+                                    &attest_key_characteristics, &attest_key_cert_chain));
 
         ASSERT_GT(attest_key_cert_chain.size(), 0);
         EXPECT_EQ(attest_key_cert_chain.size(), 1);
@@ -227,17 +255,17 @@
     AttestationKey attest_key;
     vector<KeyCharacteristics> attest_key_characteristics;
     vector<Certificate> attest_key_cert_chain;
-    auto result = GenerateKey(AuthorizationSetBuilder()
-                                      .RsaKey(2048, 65537)
-                                      .AttestKey()
-                                      .AttestationChallenge(challenge)
-                                      .AttestationApplicationId(app_id)
-                                      .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
-                                      .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
-                                      .Authorization(TAG_NO_AUTH_REQUIRED)
-                                      .SetDefaultValidity(),
-                              {} /* attestation signing key */, &attest_key.keyBlob,
-                              &attest_key_characteristics, &attest_key_cert_chain);
+    auto result = GenerateAttestKey(AuthorizationSetBuilder()
+                                            .RsaKey(2048, 65537)
+                                            .AttestKey()
+                                            .AttestationChallenge(challenge)
+                                            .AttestationApplicationId(app_id)
+                                            .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
+                                            .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
+                                            .Authorization(TAG_NO_AUTH_REQUIRED)
+                                            .SetDefaultValidity(),
+                                    {} /* attestation signing key */, &attest_key.keyBlob,
+                                    &attest_key_characteristics, &attest_key_cert_chain);
     // Strongbox may not support factory provisioned attestation key.
     if (SecLevel() == SecurityLevel::STRONGBOX) {
         if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
@@ -331,17 +359,17 @@
             attest_key_opt = attest_key;
         }
 
-        auto result = GenerateKey(AuthorizationSetBuilder()
-                                          .RsaKey(2048, 65537)
-                                          .AttestKey()
-                                          .AttestationChallenge("foo")
-                                          .AttestationApplicationId("bar")
-                                          .Authorization(TAG_NO_AUTH_REQUIRED)
-                                          .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
-                                          .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
-                                          .SetDefaultValidity(),
-                                  attest_key_opt, &key_blob_list[i], &attested_key_characteristics,
-                                  &cert_chain_list[i]);
+        auto result = GenerateAttestKey(AuthorizationSetBuilder()
+                                                .RsaKey(2048, 65537)
+                                                .AttestKey()
+                                                .AttestationChallenge("foo")
+                                                .AttestationApplicationId("bar")
+                                                .Authorization(TAG_NO_AUTH_REQUIRED)
+                                                .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
+                                                .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
+                                                .SetDefaultValidity(),
+                                        attest_key_opt, &key_blob_list[i],
+                                        &attested_key_characteristics, &cert_chain_list[i]);
         // Strongbox may not support factory provisioned attestation key.
         if (SecLevel() == SecurityLevel::STRONGBOX) {
             if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
@@ -408,17 +436,17 @@
             attest_key_opt = attest_key;
         }
 
-        auto result = GenerateKey(AuthorizationSetBuilder()
-                                          .EcdsaKey(EcCurve::P_256)
-                                          .AttestKey()
-                                          .AttestationChallenge("foo")
-                                          .AttestationApplicationId("bar")
-                                          .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
-                                          .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
-                                          .Authorization(TAG_NO_AUTH_REQUIRED)
-                                          .SetDefaultValidity(),
-                                  attest_key_opt, &key_blob_list[i], &attested_key_characteristics,
-                                  &cert_chain_list[i]);
+        auto result = GenerateAttestKey(AuthorizationSetBuilder()
+                                                .EcdsaKey(EcCurve::P_256)
+                                                .AttestKey()
+                                                .AttestationChallenge("foo")
+                                                .AttestationApplicationId("bar")
+                                                .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
+                                                .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
+                                                .Authorization(TAG_NO_AUTH_REQUIRED)
+                                                .SetDefaultValidity(),
+                                        attest_key_opt, &key_blob_list[i],
+                                        &attested_key_characteristics, &cert_chain_list[i]);
         // Strongbox may not support factory provisioned attestation key.
         if (SecLevel() == SecurityLevel::STRONGBOX) {
             if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
@@ -513,29 +541,29 @@
         }
         ErrorCode result;
         if ((i & 0x1) == 1) {
-            result = GenerateKey(AuthorizationSetBuilder()
-                                         .EcdsaKey(EcCurve::P_256)
-                                         .AttestKey()
-                                         .AttestationChallenge("foo")
-                                         .AttestationApplicationId("bar")
-                                         .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
-                                         .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
-                                         .Authorization(TAG_NO_AUTH_REQUIRED)
-                                         .SetDefaultValidity(),
-                                 attest_key_opt, &key_blob_list[i], &attested_key_characteristics,
-                                 &cert_chain_list[i]);
+            result = GenerateAttestKey(AuthorizationSetBuilder()
+                                               .EcdsaKey(EcCurve::P_256)
+                                               .AttestKey()
+                                               .AttestationChallenge("foo")
+                                               .AttestationApplicationId("bar")
+                                               .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
+                                               .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
+                                               .Authorization(TAG_NO_AUTH_REQUIRED)
+                                               .SetDefaultValidity(),
+                                       attest_key_opt, &key_blob_list[i],
+                                       &attested_key_characteristics, &cert_chain_list[i]);
         } else {
-            result = GenerateKey(AuthorizationSetBuilder()
-                                         .RsaKey(2048, 65537)
-                                         .AttestKey()
-                                         .AttestationChallenge("foo")
-                                         .AttestationApplicationId("bar")
-                                         .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
-                                         .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
-                                         .Authorization(TAG_NO_AUTH_REQUIRED)
-                                         .SetDefaultValidity(),
-                                 attest_key_opt, &key_blob_list[i], &attested_key_characteristics,
-                                 &cert_chain_list[i]);
+            result = GenerateAttestKey(AuthorizationSetBuilder()
+                                               .RsaKey(2048, 65537)
+                                               .AttestKey()
+                                               .AttestationChallenge("foo")
+                                               .AttestationApplicationId("bar")
+                                               .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
+                                               .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
+                                               .Authorization(TAG_NO_AUTH_REQUIRED)
+                                               .SetDefaultValidity(),
+                                       attest_key_opt, &key_blob_list[i],
+                                       &attested_key_characteristics, &cert_chain_list[i]);
         }
         // Strongbox may not support factory provisioned attestation key.
         if (SecLevel() == SecurityLevel::STRONGBOX) {
@@ -581,12 +609,13 @@
         AttestationKey attest_key;
         vector<KeyCharacteristics> attest_key_characteristics;
         vector<Certificate> attest_key_cert_chain;
-        ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
-                                                     .RsaKey(size, 65537)
-                                                     .AttestKey()
-                                                     .SetDefaultValidity(),
-                                             {} /* attestation signing key */, &attest_key.keyBlob,
-                                             &attest_key_characteristics, &attest_key_cert_chain));
+        ASSERT_EQ(ErrorCode::OK,
+                  GenerateAttestKey(AuthorizationSetBuilder()
+                                            .RsaKey(size, 65537)
+                                            .AttestKey()
+                                            .SetDefaultValidity(),
+                                    {} /* attestation signing key */, &attest_key.keyBlob,
+                                    &attest_key_characteristics, &attest_key_cert_chain));
 
         EXPECT_EQ(attest_key_cert_chain.size(), 1);
         EXPECT_TRUE(IsSelfSigned(attest_key_cert_chain)) << "Failed on size " << size;
@@ -630,7 +659,7 @@
         vector<Certificate> attest_key_cert_chain;
         ASSERT_EQ(
                 ErrorCode::OK,
-                GenerateKey(
+                GenerateAttestKey(
                         AuthorizationSetBuilder().EcdsaKey(curve).AttestKey().SetDefaultValidity(),
                         {} /* attestation signing key */, &attest_key.keyBlob,
                         &attest_key_characteristics, &attest_key_cert_chain));
@@ -752,12 +781,13 @@
     AttestationKey attest_key;
     vector<KeyCharacteristics> attest_key_characteristics;
     vector<Certificate> attest_key_cert_chain;
-    ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
-                                                 .EcdsaKey(EcCurve::P_256)
-                                                 .AttestKey()
-                                                 .SetDefaultValidity(),
-                                         {} /* attestation signing key */, &attest_key.keyBlob,
-                                         &attest_key_characteristics, &attest_key_cert_chain));
+    ASSERT_EQ(ErrorCode::OK,
+              GenerateAttestKey(AuthorizationSetBuilder()
+                                        .EcdsaKey(EcCurve::P_256)
+                                        .AttestKey()
+                                        .SetDefaultValidity(),
+                                {} /* attestation signing key */, &attest_key.keyBlob,
+                                &attest_key_characteristics, &attest_key_cert_chain));
     attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
     ASSERT_GT(attest_key_cert_chain.size(), 0);
     EXPECT_EQ(attest_key_cert_chain.size(), 1);
@@ -816,12 +846,13 @@
     AttestationKey attest_key;
     vector<KeyCharacteristics> attest_key_characteristics;
     vector<Certificate> attest_key_cert_chain;
-    ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
-                                                 .EcdsaKey(EcCurve::P_256)
-                                                 .AttestKey()
-                                                 .SetDefaultValidity(),
-                                         {} /* attestation signing key */, &attest_key.keyBlob,
-                                         &attest_key_characteristics, &attest_key_cert_chain));
+    ASSERT_EQ(ErrorCode::OK,
+              GenerateAttestKey(AuthorizationSetBuilder()
+                                        .EcdsaKey(EcCurve::P_256)
+                                        .AttestKey()
+                                        .SetDefaultValidity(),
+                                {} /* attestation signing key */, &attest_key.keyBlob,
+                                &attest_key_characteristics, &attest_key_cert_chain));
     attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
     ASSERT_GT(attest_key_cert_chain.size(), 0);
     EXPECT_EQ(attest_key_cert_chain.size(), 1);
diff --git a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp
index be21994..46db4f0 100644
--- a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp
+++ b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp
@@ -31,7 +31,6 @@
 #include <remote_prov/remote_prov_utils.h>
 
 #include <keymaster/cppcose/cppcose.h>
-#include <keymint_support/attestation_record.h>
 #include <keymint_support/key_param_output.h>
 #include <keymint_support/keymint_utils.h>
 #include <keymint_support/openssl_utils.h>
@@ -1461,6 +1460,31 @@
     OPENSSL_free(cert_issuer);
 }
 
+int get_vsr_api_level() {
+    int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
+    if (vendor_api_level != -1) {
+        return vendor_api_level;
+    }
+
+    // Android S and older devices do not define ro.vendor.api_level
+    vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1);
+    if (vendor_api_level == -1) {
+        vendor_api_level = ::android::base::GetIntProperty("ro.board.first_api_level", -1);
+    }
+
+    int product_api_level = ::android::base::GetIntProperty("ro.product.first_api_level", -1);
+    if (product_api_level == -1) {
+        product_api_level = ::android::base::GetIntProperty("ro.build.version.sdk", -1);
+        EXPECT_NE(product_api_level, -1) << "Could not find ro.build.version.sdk";
+    }
+
+    // VSR API level is the minimum of vendor_api_level and product_api_level.
+    if (vendor_api_level == -1 || vendor_api_level > product_api_level) {
+        return product_api_level;
+    }
+    return vendor_api_level;
+}
+
 bool is_gsi_image() {
     std::ifstream ifs("/system/system_ext/etc/init/init.gsi.rc");
     return ifs.good();
@@ -1497,6 +1521,60 @@
     verify_subject(cert.get(), subject, self_signed);
 }
 
+void verify_root_of_trust(const vector<uint8_t>& verified_boot_key, bool device_locked,
+                          VerifiedBoot verified_boot_state,
+                          const vector<uint8_t>& verified_boot_hash) {
+    char property_value[PROPERTY_VALUE_MAX] = {};
+
+    if (avb_verification_enabled()) {
+        EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
+        string prop_string(property_value);
+        EXPECT_EQ(prop_string.size(), 64);
+        EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
+
+        EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
+        if (!strcmp(property_value, "unlocked")) {
+            EXPECT_FALSE(device_locked);
+        } else {
+            EXPECT_TRUE(device_locked);
+        }
+
+        // Check that the device is locked if not debuggable, e.g., user build
+        // images in CTS. For VTS, debuggable images are used to allow adb root
+        // and the device is unlocked.
+        if (!property_get_bool("ro.debuggable", false)) {
+            EXPECT_TRUE(device_locked);
+        } else {
+            EXPECT_FALSE(device_locked);
+        }
+    }
+
+    // Verified boot key should be all 0's if the boot state is not verified or self signed
+    std::string empty_boot_key(32, '\0');
+    std::string verified_boot_key_str((const char*)verified_boot_key.data(),
+                                      verified_boot_key.size());
+    EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
+    if (!strcmp(property_value, "green")) {
+        EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
+        EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
+                            verified_boot_key.size()));
+    } else if (!strcmp(property_value, "yellow")) {
+        EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
+        EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
+                            verified_boot_key.size()));
+    } else if (!strcmp(property_value, "orange")) {
+        EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
+        EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
+                            verified_boot_key.size()));
+    } else if (!strcmp(property_value, "red")) {
+        EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
+    } else {
+        EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
+        EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
+                            verified_boot_key.size()));
+    }
+}
+
 bool verify_attestation_record(int32_t aidl_version,                   //
                                const string& challenge,                //
                                const string& app_id,                   //
@@ -1551,8 +1629,6 @@
     EXPECT_EQ(security_level, att_keymint_security_level);
     EXPECT_EQ(security_level, att_attestation_security_level);
 
-
-    char property_value[PROPERTY_VALUE_MAX] = {};
     // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
     // keymint implementation will report YYYYMM dates instead of YYYYMMDD
     // for the BOOT_PATCH_LEVEL.
@@ -1612,54 +1688,7 @@
     error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
                                 &verified_boot_state, &device_locked, &verified_boot_hash);
     EXPECT_EQ(ErrorCode::OK, error);
-
-    if (avb_verification_enabled()) {
-        EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
-        string prop_string(property_value);
-        EXPECT_EQ(prop_string.size(), 64);
-        EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
-
-        EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
-        if (!strcmp(property_value, "unlocked")) {
-            EXPECT_FALSE(device_locked);
-        } else {
-            EXPECT_TRUE(device_locked);
-        }
-
-        // Check that the device is locked if not debuggable, e.g., user build
-        // images in CTS. For VTS, debuggable images are used to allow adb root
-        // and the device is unlocked.
-        if (!property_get_bool("ro.debuggable", false)) {
-            EXPECT_TRUE(device_locked);
-        } else {
-            EXPECT_FALSE(device_locked);
-        }
-    }
-
-    // Verified boot key should be all 0's if the boot state is not verified or self signed
-    std::string empty_boot_key(32, '\0');
-    std::string verified_boot_key_str((const char*)verified_boot_key.data(),
-                                      verified_boot_key.size());
-    EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
-    if (!strcmp(property_value, "green")) {
-        EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
-        EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
-                            verified_boot_key.size()));
-    } else if (!strcmp(property_value, "yellow")) {
-        EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
-        EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
-                            verified_boot_key.size()));
-    } else if (!strcmp(property_value, "orange")) {
-        EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
-        EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
-                            verified_boot_key.size()));
-    } else if (!strcmp(property_value, "red")) {
-        EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
-    } else {
-        EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
-        EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
-                            verified_boot_key.size()));
-    }
+    verify_root_of_trust(verified_boot_key, device_locked, verified_boot_state, verified_boot_hash);
 
     att_sw_enforced.Sort();
     expected_sw_enforced.Sort();
diff --git a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h
index 2634ab7..8f9df24 100644
--- a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h
+++ b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h
@@ -31,6 +31,7 @@
 #include <aidl/android/hardware/security/keymint/IKeyMintDevice.h>
 #include <aidl/android/hardware/security/keymint/MacedPublicKey.h>
 
+#include <keymint_support/attestation_record.h>
 #include <keymint_support/authorization_set.h>
 #include <keymint_support/openssl_utils.h>
 
@@ -354,6 +355,9 @@
     }
 }
 
+// Return the VSR API level for this device.
+int get_vsr_api_level();
+
 // Indicate whether the test is running on a GSI image.
 bool is_gsi_image();
 
@@ -363,7 +367,10 @@
 void verify_subject_and_serial(const Certificate& certificate,  //
                                const uint64_t expected_serial,  //
                                const string& subject, bool self_signed);
-
+void verify_root_of_trust(const vector<uint8_t>& verified_boot_key,  //
+                          bool device_locked,                        //
+                          VerifiedBoot verified_boot_state,          //
+                          const vector<uint8_t>& verified_boot_hash);
 bool verify_attestation_record(int aidl_version,                       //
                                const string& challenge,                //
                                const string& app_id,                   //
diff --git a/security/keymint/aidl/vts/functional/KeyMintTest.cpp b/security/keymint/aidl/vts/functional/KeyMintTest.cpp
index 3c2bece..4e746b2 100644
--- a/security/keymint/aidl/vts/functional/KeyMintTest.cpp
+++ b/security/keymint/aidl/vts/functional/KeyMintTest.cpp
@@ -7991,6 +7991,18 @@
 
 INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
 
+using VsrRequirementTest = KeyMintAidlTestBase;
+
+TEST_P(VsrRequirementTest, Vsr13Test) {
+    int vsr_api_level = get_vsr_api_level();
+    if (vsr_api_level < 33) {
+        GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
+    }
+    EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
+}
+
+INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
+
 }  // namespace aidl::android::hardware::security::keymint::test
 
 int main(int argc, char** argv) {
diff --git a/security/keymint/aidl/vts/functional/SecureElementProvisioningTest.cpp b/security/keymint/aidl/vts/functional/SecureElementProvisioningTest.cpp
index e630f70..c9a156d 100644
--- a/security/keymint/aidl/vts/functional/SecureElementProvisioningTest.cpp
+++ b/security/keymint/aidl/vts/functional/SecureElementProvisioningTest.cpp
@@ -36,6 +36,8 @@
 using std::shared_ptr;
 using std::vector;
 
+constexpr int kRoTVersion1 = 40001;
+
 class SecureElementProvisioningTest : public testing::Test {
   protected:
     static void SetUpTestSuite() {
@@ -57,6 +59,83 @@
         }
     }
 
+    void validateMacedRootOfTrust(const vector<uint8_t>& rootOfTrust) {
+        SCOPED_TRACE(testing::Message() << "RoT: " << bin2hex(rootOfTrust));
+
+        const auto [macItem, macEndPos, macErrMsg] = cppbor::parse(rootOfTrust);
+        ASSERT_TRUE(macItem) << "Root of trust parsing failed: " << macErrMsg;
+        ASSERT_EQ(macItem->semanticTagCount(), 1);
+        ASSERT_EQ(macItem->semanticTag(0), cppcose::kCoseMac0SemanticTag);
+        ASSERT_TRUE(macItem->asArray());
+        ASSERT_EQ(macItem->asArray()->size(), cppcose::kCoseMac0EntryCount);
+
+        const auto& protectedItem = macItem->asArray()->get(cppcose::kCoseMac0ProtectedParams);
+        ASSERT_TRUE(protectedItem);
+        ASSERT_TRUE(protectedItem->asBstr());
+        const auto [protMap, protEndPos, protErrMsg] = cppbor::parse(protectedItem->asBstr());
+        ASSERT_TRUE(protMap);
+        ASSERT_TRUE(protMap->asMap());
+        ASSERT_EQ(protMap->asMap()->size(), 1);
+
+        const auto& algorithm = protMap->asMap()->get(cppcose::ALGORITHM);
+        ASSERT_TRUE(algorithm);
+        ASSERT_TRUE(algorithm->asInt());
+        ASSERT_EQ(algorithm->asInt()->value(), cppcose::HMAC_256);
+
+        const auto& unprotItem = macItem->asArray()->get(cppcose::kCoseMac0UnprotectedParams);
+        ASSERT_TRUE(unprotItem);
+        ASSERT_TRUE(unprotItem->asMap());
+        ASSERT_EQ(unprotItem->asMap()->size(), 0);
+
+        const auto& payload = macItem->asArray()->get(cppcose::kCoseMac0Payload);
+        ASSERT_TRUE(payload);
+        ASSERT_TRUE(payload->asBstr());
+        validateRootOfTrust(payload->asBstr()->value());
+
+        const auto& tag = macItem->asArray()->get(cppcose::kCoseMac0Tag);
+        ASSERT_TRUE(tag);
+        ASSERT_TRUE(tag->asBstr());
+        ASSERT_EQ(tag->asBstr()->value().size(), 32);
+        // Cannot validate tag correctness.  Only the secure side has the necessary key.
+    }
+
+    void validateRootOfTrust(const vector<uint8_t>& payload) {
+        SCOPED_TRACE(testing::Message() << "RoT payload: " << bin2hex(payload));
+
+        const auto [rot, rotPos, rotErrMsg] = cppbor::parse(payload);
+        ASSERT_TRUE(rot);
+        ASSERT_EQ(rot->semanticTagCount(), 1);
+        ASSERT_EQ(rot->semanticTag(), kRoTVersion1);
+        ASSERT_TRUE(rot->asArray());
+        ASSERT_EQ(rot->asArray()->size(), 5);
+
+        size_t pos = 0;
+
+        const auto& vbKey = rot->asArray()->get(pos++);
+        ASSERT_TRUE(vbKey);
+        ASSERT_TRUE(vbKey->asBstr());
+
+        const auto& deviceLocked = rot->asArray()->get(pos++);
+        ASSERT_TRUE(deviceLocked);
+        ASSERT_TRUE(deviceLocked->asBool());
+
+        const auto& verifiedBootState = rot->asArray()->get(pos++);
+        ASSERT_TRUE(verifiedBootState);
+        ASSERT_TRUE(verifiedBootState->asInt());
+
+        const auto& verifiedBootHash = rot->asArray()->get(pos++);
+        ASSERT_TRUE(verifiedBootHash);
+        ASSERT_TRUE(verifiedBootHash->asBstr());
+
+        const auto& bootPatchLevel = rot->asArray()->get(pos++);
+        ASSERT_TRUE(bootPatchLevel);
+        ASSERT_TRUE(bootPatchLevel->asInt());
+
+        verify_root_of_trust(vbKey->asBstr()->value(), deviceLocked->asBool()->value(),
+                             static_cast<VerifiedBoot>(verifiedBootState->asInt()->value()),
+                             verifiedBootHash->asBstr()->value());
+    }
+
     int32_t AidlVersion(shared_ptr<IKeyMintDevice> keymint) {
         int32_t version = 0;
         auto status = keymint->getInterfaceVersion(&version);
@@ -96,29 +175,19 @@
 
     vector<uint8_t> rootOfTrust1;
     Status result = tee->getRootOfTrust(challenge1, &rootOfTrust1);
-
-    // TODO: Remove the next line to require TEEs to succeed.
-    if (!result.isOk()) return;
-
-    ASSERT_TRUE(result.isOk());
-
-    // TODO:  Parse and validate rootOfTrust1 here
+    ASSERT_TRUE(result.isOk()) << "getRootOfTrust returned " << result.getServiceSpecificError();
+    validateMacedRootOfTrust(rootOfTrust1);
 
     vector<uint8_t> rootOfTrust2;
     result = tee->getRootOfTrust(challenge2, &rootOfTrust2);
     ASSERT_TRUE(result.isOk());
-
-    // TODO:  Parse and validate rootOfTrust2 here
-
+    validateMacedRootOfTrust(rootOfTrust2);
     ASSERT_NE(rootOfTrust1, rootOfTrust2);
 
     vector<uint8_t> rootOfTrust3;
     result = tee->getRootOfTrust(challenge1, &rootOfTrust3);
     ASSERT_TRUE(result.isOk());
-
     ASSERT_EQ(rootOfTrust1, rootOfTrust3);
-
-    // TODO:  Parse and validate rootOfTrust3 here
 }
 
 TEST_F(SecureElementProvisioningTest, TeeDoesNotImplementStrongBoxMethods) {
@@ -252,7 +321,7 @@
     result = tee->getRootOfTrust(challenge, &rootOfTrust);
     ASSERT_TRUE(result.isOk());
 
-    // TODO: Verify COSE_Mac0 structure and content here.
+    validateMacedRootOfTrust(rootOfTrust);
 
     result = sb->sendRootOfTrust(rootOfTrust);
     ASSERT_TRUE(result.isOk());
@@ -296,6 +365,8 @@
     result = tee->getRootOfTrust(challenge, &rootOfTrust);
     ASSERT_TRUE(result.isOk());
 
+    validateMacedRootOfTrust(rootOfTrust);
+
     vector<uint8_t> corruptedRootOfTrust = rootOfTrust;
     corruptedRootOfTrust[corruptedRootOfTrust.size() / 2]++;
     result = sb->sendRootOfTrust(corruptedRootOfTrust);
diff --git a/sensors/1.0/vts/functional/Android.bp b/sensors/1.0/vts/functional/Android.bp
index 274cfa7..d53179a 100644
--- a/sensors/1.0/vts/functional/Android.bp
+++ b/sensors/1.0/vts/functional/Android.bp
@@ -26,7 +26,10 @@
 cc_test {
     name: "VtsHalSensorsV1_0TargetTest",
     cflags: ["-DLOG_TAG=\"sensors_hidl_hal_test\""],
-    defaults: ["VtsHalTargetTestDefaults"],
+    defaults: [
+        "VtsHalSensorsDefaults",
+        "VtsHalTargetTestDefaults",
+    ],
     tidy_timeout_srcs: [
         "VtsHalSensorsV1_0TargetTest.cpp",
     ],
@@ -34,9 +37,12 @@
         "SensorsHidlEnvironmentV1_0.cpp",
         "VtsHalSensorsV1_0TargetTest.cpp",
     ],
+    shared_libs: [
+        "libbinder_ndk",
+        "libvndksupport",
+    ],
     static_libs: [
         "android.hardware.sensors@1.0",
-        "VtsHalSensorsTargetTestUtils",
     ],
     test_suites: [
         "general-tests",
diff --git a/sensors/2.0/vts/functional/Android.bp b/sensors/2.0/vts/functional/Android.bp
index c4ec866..62eaf6b 100644
--- a/sensors/2.0/vts/functional/Android.bp
+++ b/sensors/2.0/vts/functional/Android.bp
@@ -26,7 +26,10 @@
 cc_test {
     name: "VtsHalSensorsV2_0TargetTest",
     cflags: ["-DLOG_TAG=\"sensors_hidl_hal_test\""],
-    defaults: ["VtsHalTargetTestDefaults"],
+    defaults: [
+        "VtsHalSensorsDefaults",
+        "VtsHalTargetTestDefaults",
+    ],
     tidy_timeout_srcs: [
         "VtsHalSensorsV2_0TargetTest.cpp",
     ],
@@ -36,13 +39,15 @@
     header_libs: [
         "android.hardware.sensors@2.X-shared-utils",
     ],
+    shared_libs: [
+        "libbinder_ndk",
+    ],
     static_libs: [
         "android.hardware.sensors@1.0",
         "android.hardware.sensors@1.0-convert",
         "android.hardware.sensors@2.0",
         "android.hardware.sensors@2.1",
         "libfmq",
-        "VtsHalSensorsTargetTestUtils",
         "VtsHalSensorsV2_0TargetTest-lib",
     ],
     test_suites: [
diff --git a/sensors/2.1/vts/functional/Android.bp b/sensors/2.1/vts/functional/Android.bp
index 3659e11..61cfd14 100644
--- a/sensors/2.1/vts/functional/Android.bp
+++ b/sensors/2.1/vts/functional/Android.bp
@@ -28,7 +28,10 @@
     cflags: [
         "-DLOG_TAG=\"sensors_hidl_hal_test\"",
     ],
-    defaults: ["VtsHalTargetTestDefaults"],
+    defaults: [
+        "VtsHalSensorsDefaults",
+        "VtsHalTargetTestDefaults",
+    ],
     srcs: [
         "VtsHalSensorsV2_1TargetTest.cpp",
     ],
@@ -41,7 +44,6 @@
         "android.hardware.sensors@2.0",
         "android.hardware.sensors@2.1",
         "libfmq",
-        "VtsHalSensorsTargetTestUtils",
         "VtsHalSensorsV2_1TargetTest-lib",
     ],
     test_suites: [
diff --git a/sensors/aidl/default/multihal/ConvertUtils.cpp b/sensors/aidl/default/multihal/ConvertUtils.cpp
index 9b2d8fe..bf56ed5 100644
--- a/sensors/aidl/default/multihal/ConvertUtils.cpp
+++ b/sensors/aidl/default/multihal/ConvertUtils.cpp
@@ -77,6 +77,8 @@
             hidlEvent->u.vec3.x = aidlEvent.payload.get<Event::EventPayload::vec3>().x;
             hidlEvent->u.vec3.y = aidlEvent.payload.get<Event::EventPayload::vec3>().y;
             hidlEvent->u.vec3.z = aidlEvent.payload.get<Event::EventPayload::vec3>().z;
+            hidlEvent->u.vec3.status =
+                    (V1_0SensorStatus)aidlEvent.payload.get<Event::EventPayload::vec3>().status;
             break;
         case AidlSensorType::GAME_ROTATION_VECTOR:
             hidlEvent->u.vec4.x = aidlEvent.payload.get<Event::EventPayload::vec4>().x;
@@ -225,6 +227,7 @@
             vec3.x = hidlEvent.u.vec3.x;
             vec3.y = hidlEvent.u.vec3.y;
             vec3.z = hidlEvent.u.vec3.z;
+            vec3.status = (SensorStatus)hidlEvent.u.vec3.status;
             aidlEvent->payload.set<Event::EventPayload::vec3>(vec3);
             break;
         }
diff --git a/sensors/aidl/vts/Android.bp b/sensors/aidl/vts/Android.bp
index b5a5f15..f3972ec 100644
--- a/sensors/aidl/vts/Android.bp
+++ b/sensors/aidl/vts/Android.bp
@@ -24,8 +24,9 @@
 cc_test {
     name: "VtsAidlHalSensorsTargetTest",
     defaults: [
-        "VtsHalTargetTestDefaults",
         "use_libaidlvintf_gtest_helper_static",
+        "VtsHalSensorsDefaults",
+        "VtsHalTargetTestDefaults",
     ],
     srcs: [
         "VtsAidlHalSensorsTargetTest.cpp",
diff --git a/sensors/aidl/vts/AndroidTest.xml b/sensors/aidl/vts/AndroidTest.xml
new file mode 100644
index 0000000..99caf28
--- /dev/null
+++ b/sensors/aidl/vts/AndroidTest.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+<configuration description="Runs VtsAidlHalSensorsTargetTest.">
+    <option name="test-suite-tag" value="apct" />
+    <option name="test-suite-tag" value="apct-native" />
+
+    <target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer"/>
+    <target_preparer class="com.android.tradefed.targetprep.StopServicesSetup"/>
+
+    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+        <option name="cleanup" value="true" />
+        <option name="push" value="VtsAidlHalSensorsTargetTest->/data/local/tmp/VtsAidlHalSensorsTargetTest" />
+    </target_preparer>
+
+    <test class="com.android.tradefed.testtype.GTest" >
+        <option name="native-test-timeout" value="900000" />
+        <option name="runtime-hint" value="300000"/>
+        <option name="native-test-device-path" value="/data/local/tmp" />
+        <option name="module-name" value="VtsAidlHalSensorsTargetTest" />
+    </test>
+</configuration>
diff --git a/sensors/common/vts/utils/Android.bp b/sensors/common/vts/utils/Android.bp
index 44bed6e..08b6afa 100644
--- a/sensors/common/vts/utils/Android.bp
+++ b/sensors/common/vts/utils/Android.bp
@@ -23,6 +23,23 @@
     default_applicable_licenses: ["hardware_interfaces_license"],
 }
 
+// Prefer to use these defaults to pull in VtsHalSensorsTargetTestUtils + its
+// dependencies
+cc_defaults {
+    name: "VtsHalSensorsDefaults",
+    shared_libs: [
+        "android.hardware.graphics.allocator-V1-ndk",
+        "android.hardware.graphics.common-V3-ndk",
+        "libbinder_ndk",
+        "libutils",
+        "libvndksupport",
+    ],
+    static_libs: [
+        "libaidlcommonsupport",
+        "VtsHalSensorsTargetTestUtils",
+    ],
+}
+
 cc_library_static {
     name: "VtsHalSensorsTargetTestUtils",
     defaults: ["VtsHalTargetTestDefaults"],
@@ -36,13 +53,19 @@
     local_include_dirs: [
         "include/sensors-vts-utils",
     ],
+    // Targets that depend on us need to also include these
     shared_libs: [
+        "android.hardware.graphics.allocator-V1-ndk",
+        "android.hardware.graphics.common-V3-ndk",
+        "libbinder_ndk",
         "libutils",
+        "libvndksupport",
     ],
     static_libs: [
         "android.hardware.sensors@1.0",
         "android.hardware.sensors@2.0",
         "android.hardware.sensors@2.1",
+        "libaidlcommonsupport",
     ],
     whole_static_libs: [
         "android.hardware.graphics.allocator@2.0",
diff --git a/sensors/common/vts/utils/GrallocWrapper.cpp b/sensors/common/vts/utils/GrallocWrapper.cpp
index 47d1f42..e6e0888 100644
--- a/sensors/common/vts/utils/GrallocWrapper.cpp
+++ b/sensors/common/vts/utils/GrallocWrapper.cpp
@@ -16,6 +16,9 @@
 
 #include "GrallocWrapper.h"
 
+#include <aidl/android/hardware/graphics/allocator/IAllocator.h>
+#include <aidlcommonsupport/NativeHandle.h>
+#include <android/binder_manager.h>
 #include <android/hardware/graphics/allocator/2.0/IAllocator.h>
 #include <android/hardware/graphics/allocator/3.0/IAllocator.h>
 #include <android/hardware/graphics/allocator/4.0/IAllocator.h>
@@ -27,8 +30,10 @@
 #include <utils/Log.h>
 
 #include <cinttypes>
+#include <memory>
 #include <type_traits>
 
+using IAllocatorAidl = ::aidl::android::hardware::graphics::allocator::IAllocator;
 using IAllocator2 = ::android::hardware::graphics::allocator::V2_0::IAllocator;
 using IAllocator3 = ::android::hardware::graphics::allocator::V3_0::IAllocator;
 using IAllocator4 = ::android::hardware::graphics::allocator::V4_0::IAllocator;
@@ -41,6 +46,9 @@
 using Error3 = ::android::hardware::graphics::mapper::V3_0::Error;
 using Error4 = ::android::hardware::graphics::mapper::V4_0::Error;
 
+using ::aidl::android::hardware::common::NativeHandle;
+using ::aidl::android::hardware::graphics::allocator::AllocationResult;
+
 using ::android::hardware::graphics::common::V1_0::BufferUsage;
 using ::android::hardware::graphics::common::V1_0::PixelFormat;
 
@@ -97,10 +105,11 @@
 
 // Since all the type and function names are the same for the things we use across the major HAL
 // versions, we use template magic to avoid repeating ourselves.
-template <typename AllocatorT, typename MapperT>
+template <typename AllocatorT, typename MapperT,
+          template <typename> typename AllocatorWrapperT = sp>
 class GrallocHalWrapper : public IGrallocHalWrapper {
   public:
-    GrallocHalWrapper(const sp<AllocatorT>& allocator, const sp<MapperT>& mapper)
+    GrallocHalWrapper(const AllocatorWrapperT<AllocatorT>& allocator, const sp<MapperT>& mapper)
         : mAllocator(allocator), mMapper(mapper) {
         if (mapper->isRemote()) {
             ALOGE("Mapper is in passthrough mode");
@@ -116,7 +125,7 @@
   private:
     static constexpr uint64_t kBufferUsage =
             static_cast<uint64_t>(BufferUsage::SENSOR_DIRECT_DATA | BufferUsage::CPU_READ_OFTEN);
-    sp<AllocatorT> mAllocator;
+    AllocatorWrapperT<AllocatorT> mAllocator;
     sp<MapperT> mMapper;
 
     // v2.0 and v3.0 use vec<uint32_t> for BufferDescriptor, but v4.0 uses vec<uint8_t>, so use
@@ -128,8 +137,34 @@
     native_handle_t* importBuffer(const hidl_handle& rawHandle);
 };
 
-template <typename AllocatorT, typename MapperT>
-native_handle_t* GrallocHalWrapper<AllocatorT, MapperT>::allocate(uint32_t size) {
+template <>
+native_handle_t* GrallocHalWrapper<IAllocatorAidl, IMapper4, std::shared_ptr>::allocate(
+        uint32_t size) {
+    constexpr uint32_t kBufferCount = 1;
+    BufferDescriptorT descriptor = getDescriptor(size);
+    native_handle_t* bufferHandle = nullptr;
+
+    AllocationResult result;
+    auto status = mAllocator->allocate(descriptor, kBufferCount, &result);
+    if (!status.isOk()) {
+        status_t error = status.getExceptionCode();
+        ALOGE("Failed to allocate buffer: %" PRId32, static_cast<int32_t>(error));
+    } else if (result.buffers.size() != kBufferCount) {
+        ALOGE("Invalid buffer array size (got %zu, expected %" PRIu32 ")", result.buffers.size(),
+              kBufferCount);
+    } else {
+        // Convert from AIDL NativeHandle to native_handle_t to hidl_handle
+        hidl_handle hidlHandle;
+        hidlHandle.setTo(dupFromAidl(result.buffers[0]), /*shouldOwn*/ true);
+        bufferHandle = importBuffer(hidlHandle);
+    }
+
+    return bufferHandle;
+}
+
+template <typename AllocatorT, typename MapperT, template <typename> typename AllocatorWrapperT>
+native_handle_t* GrallocHalWrapper<AllocatorT, MapperT, AllocatorWrapperT>::allocate(
+        uint32_t size) {
     constexpr uint32_t kBufferCount = 1;
     BufferDescriptorT descriptor = getDescriptor(size);
     native_handle_t* bufferHandle = nullptr;
@@ -149,17 +184,18 @@
     return bufferHandle;
 }
 
-template <typename AllocatorT, typename MapperT>
-void GrallocHalWrapper<AllocatorT, MapperT>::freeBuffer(native_handle_t* bufferHandle) {
+template <typename AllocatorT, typename MapperT, template <typename> typename AllocatorWrapperT>
+void GrallocHalWrapper<AllocatorT, MapperT, AllocatorWrapperT>::freeBuffer(
+        native_handle_t* bufferHandle) {
     auto error = mMapper->freeBuffer(bufferHandle);
     if (!error.isOk() || failed(error)) {
         ALOGE("Failed to free buffer %p", bufferHandle);
     }
 }
 
-template <typename AllocatorT, typename MapperT>
-typename GrallocHalWrapper<AllocatorT, MapperT>::BufferDescriptorT
-GrallocHalWrapper<AllocatorT, MapperT>::getDescriptor(uint32_t size) {
+template <typename AllocatorT, typename MapperT, template <typename> typename AllocatorWrapperT>
+typename GrallocHalWrapper<AllocatorT, MapperT, AllocatorWrapperT>::BufferDescriptorT
+GrallocHalWrapper<AllocatorT, MapperT, AllocatorWrapperT>::getDescriptor(uint32_t size) {
     typename MapperT::BufferDescriptorInfo descriptorInfo = {
             .width = size,
             .height = 1,
@@ -181,8 +217,8 @@
     return descriptor;
 }
 
-template <typename AllocatorT, typename MapperT>
-native_handle_t* GrallocHalWrapper<AllocatorT, MapperT>::importBuffer(
+template <typename AllocatorT, typename MapperT, template <typename> typename AllocatorWrapperT>
+native_handle_t* GrallocHalWrapper<AllocatorT, MapperT, AllocatorWrapperT>::importBuffer(
         const hidl_handle& rawHandle) {
     native_handle_t* bufferHandle = nullptr;
 
@@ -198,8 +234,9 @@
     return bufferHandle;
 }
 
-template <typename AllocatorT, typename MapperT>
-void* GrallocHalWrapper<AllocatorT, MapperT>::lock(native_handle_t* bufferHandle) {
+template <typename AllocatorT, typename MapperT, template <typename> typename AllocatorWrapperT>
+void* GrallocHalWrapper<AllocatorT, MapperT, AllocatorWrapperT>::lock(
+        native_handle_t* bufferHandle) {
     // Per the HAL, all-zeros Rect means the entire buffer
     typename MapperT::Rect accessRegion = {};
     hidl_handle acquireFenceHandle;  // No fence needed, already safe to lock
@@ -218,8 +255,9 @@
     return data;
 }
 
-template <typename AllocatorT, typename MapperT>
-void GrallocHalWrapper<AllocatorT, MapperT>::unlock(native_handle_t* bufferHandle) {
+template <typename AllocatorT, typename MapperT, template <typename> typename AllocatorWrapperT>
+void GrallocHalWrapper<AllocatorT, MapperT, AllocatorWrapperT>::unlock(
+        native_handle_t* bufferHandle) {
     mMapper->unlock(bufferHandle, [&](auto error, const hidl_handle& /*releaseFence*/) {
         if (failed(error)) {
             ALOGE("Failed to unlock buffer %p: %" PRId32, bufferHandle,
@@ -234,8 +272,22 @@
     sp<IAllocator4> allocator4 = IAllocator4::getService();
     sp<IMapper4> mapper4 = IMapper4::getService();
 
-    if (allocator4 != nullptr && mapper4 != nullptr) {
-        ALOGD("Using IAllocator/IMapper v4.0");
+    const auto kAllocatorSvc = std::string(IAllocatorAidl::descriptor) + "/default";
+    std::shared_ptr<IAllocatorAidl> allocatorAidl;
+    if (AServiceManager_isDeclared(kAllocatorSvc.c_str())) {
+        allocatorAidl = IAllocatorAidl::fromBinder(
+                ndk::SpAIBinder(AServiceManager_checkService(kAllocatorSvc.c_str())));
+    }
+
+    // As of T, AIDL Allocator is supported only with HIDL Mapper4
+    // (ref: VtsHalGraphicsAllocatorAidl_TargetTest.cpp)
+    if (allocatorAidl != nullptr && mapper4 != nullptr) {
+        ALOGD("Using AIDL IAllocator + HIDL IMapper v4.0");
+        mGrallocHal = std::unique_ptr<IGrallocHalWrapper>(
+                new GrallocHalWrapper<IAllocatorAidl, IMapper4, std::shared_ptr>(allocatorAidl,
+                                                                                 mapper4));
+    } else if (allocator4 != nullptr && mapper4 != nullptr) {
+        ALOGD("AIDL IAllocator not found, using HIDL IAllocator/IMapper v4.0");
         mGrallocHal = std::unique_ptr<IGrallocHalWrapper>(
                 new GrallocHalWrapper<IAllocator4, IMapper4>(allocator4, mapper4));
     } else {
diff --git a/tv/tuner/1.0/vts/functional/VtsHalTvTunerV1_0TargetTest.cpp b/tv/tuner/1.0/vts/functional/VtsHalTvTunerV1_0TargetTest.cpp
index 3e3a4d4..59b7939 100644
--- a/tv/tuner/1.0/vts/functional/VtsHalTvTunerV1_0TargetTest.cpp
+++ b/tv/tuner/1.0/vts/functional/VtsHalTvTunerV1_0TargetTest.cpp
@@ -144,9 +144,9 @@
     ASSERT_TRUE(mFilterTests.getNewlyOpenedFilterId(filterId));
     ASSERT_TRUE(mFilterTests.configFilter(filterConf.settings, filterId));
     ASSERT_TRUE(mFilterTests.getFilterMQDescriptor(filterId, filterConf.getMqDesc));
-    mDvrTests.startPlaybackInputThread(dvrConf.playbackInputFile, dvrConf.settings.playback());
     ASSERT_TRUE(mDvrTests.startDvrPlayback());
     ASSERT_TRUE(mFilterTests.startFilter(filterId));
+    mDvrTests.startPlaybackInputThread(dvrConf.playbackInputFile, dvrConf.settings.playback());
     ASSERT_TRUE(filterDataOutputTest());
     mDvrTests.stopPlaybackThread();
     ASSERT_TRUE(mFilterTests.stopFilter(filterId));
diff --git a/uwb/aidl/Android.bp b/uwb/aidl/Android.bp
index cc61046..3981724 100755
--- a/uwb/aidl/Android.bp
+++ b/uwb/aidl/Android.bp
@@ -50,6 +50,7 @@
 
 aidl_interface {
     name: "android.hardware.uwb.fira_android",
+    owner: "google",
     vendor_available: true,
     srcs: ["android/hardware/uwb/fira_android/*.aidl"],
     stability: "vintf",
diff --git a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl
index cbe2068..39bb5d9 100644
--- a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl
+++ b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl
@@ -44,4 +44,8 @@
   CCC_SUPPORTED_PULSE_SHAPE_COMBOS = 166,
   CCC_SUPPORTED_RAN_MULTIPLIER = 167,
   SUPPORTED_AOA_RESULT_REQ_ANTENNA_INTERLEAVING = 227,
+  SUPPORTED_MIN_RANGING_INTERVAL_MS = 228,
+  SUPPORTED_RANGE_DATA_NTF_CONFIG = 229,
+  SUPPORTED_RSSI_REPORTING = 230,
+  SUPPORTED_DIAGNOSTICS = 231,
 }
diff --git a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl
index cd2e122..fbcfbff 100644
--- a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl
+++ b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl
@@ -36,4 +36,5 @@
 enum UwbVendorGidAndroidOids {
   ANDROID_GET_POWER_STATS = 0,
   ANDROID_SET_COUNTRY_CODE = 1,
+  ANDROID_RANGE_DIAGNOSTICS = 2,
 }
diff --git a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvTypes.aidl b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvTypes.aidl
index d35728f..8413f06 100644
--- a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvTypes.aidl
+++ b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvTypes.aidl
@@ -43,4 +43,6 @@
   NB_OF_RANGE_MEASUREMENTS = 227,
   NB_OF_AZIMUTH_MEASUREMENTS = 228,
   NB_OF_ELEVATION_MEASUREMENTS = 229,
+  ENABLE_DIAGNOSTICS = 232,
+  DIAGRAMS_FRAME_REPORTS_FIELDS = 233,
 }
diff --git a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl
index 0140fdd..86479fb 100644
--- a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl
+++ b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl
@@ -150,4 +150,33 @@
      *  0 - Feature not supported.
      */
     SUPPORTED_AOA_RESULT_REQ_ANTENNA_INTERLEAVING = 0xE3,
+
+    /**
+     * 4 byte value to indicate supported min ranging interval in ms.
+     */
+    SUPPORTED_MIN_RANGING_INTERVAL_MS = 0xE4,
+
+    /**
+     * 4 byte bitmask to indicate the supported RANGE_DATA_NTF_CONFIG values
+     *
+     * Bitmask where each bit corresponds to values used in
+     * RANGE_DATA_NTF_CONFIG in SET_APP_CFG_CMD
+     */
+    SUPPORTED_RANGE_DATA_NTF_CONFIG = 0xE5,
+
+    /**
+     * 1 byte bitmask to indicate the supported RSSI_REPORTING values
+     * Values:
+     * 1 - Feature supported.
+     * 0 - Feature not supported.
+     */
+    SUPPORTED_RSSI_REPORTING = 0xE6,
+
+    /**
+     * 1 byte value to indicate support for diagnostics feature.
+     * Values:
+     *  1 - Feature supported.
+     *  0 - Feature not supported.
+     */
+    SUPPORTED_DIAGNOSTICS = 0xE7,
 }
diff --git a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl
index e389a2d..42d52f1 100644
--- a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl
+++ b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl
@@ -31,4 +31,8 @@
     // Used to set the current regulatory country code (determined usinag
     // SIM or hardcoded by OEM).
     ANDROID_SET_COUNTRY_CODE = 0x1,
+    // Used by the notification to get UWB ranging diagnostics stats.
+    // Supported only if the UwbVendorCapabilityTlvTypes.SUPPORTED_DIAGNOSTICS set
+    // to 1.
+    ANDROID_RANGE_DIAGNOSTICS = 0x2,
 }
diff --git a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvTypes.aidl b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvTypes.aidl
index f43b249..f303ed9 100644
--- a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvTypes.aidl
+++ b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvTypes.aidl
@@ -66,4 +66,23 @@
     NB_OF_AZIMUTH_MEASUREMENTS = 0xE4,
     /** 1 byte data */
     NB_OF_ELEVATION_MEASUREMENTS = 0xE5,
+
+    /**
+     * Supported only if the UwbVendorCapabilityTlvTypes
+     * .SUPPORTED_DIAGNOSTICS set to 1.
+     */
+    /**
+     * 1 byte data
+     * 1 - Enable,
+     * 0 - Disable
+     */
+    ENABLE_DIAGNOSTICS = 0xE8,
+    /**
+     * 1 byte bitmask
+     * b0: Activate RSSIs field,
+     * b1: Activate AoAs field,
+     * b2: Activate CIRs field,
+     * b3 - b7: RFU
+     */
+    DIAGRAMS_FRAME_REPORTS_FIELDS = 0xE9,
 }
diff --git a/uwb/aidl/vts/VtsHalUwbTargetTest.cpp b/uwb/aidl/vts/VtsHalUwbTargetTest.cpp
index edd8dd6..81d26ba 100644
--- a/uwb/aidl/vts/VtsHalUwbTargetTest.cpp
+++ b/uwb/aidl/vts/VtsHalUwbTargetTest.cpp
@@ -68,6 +68,11 @@
         iuwb_ = IUwb::fromBinder(SpAIBinder(AServiceManager_waitForService(GetParam().c_str())));
         ASSERT_NE(iuwb_, nullptr);
     }
+    virtual void TearDown() override {
+        // Trigger HAL close at end of each test.
+        const auto iuwb_chip = getAnyChip();
+        iuwb_chip->close();
+    }
     std::shared_ptr<IUwb> iuwb_;
 
     // TODO (b/197638976): We pick the first chip here. Need to fix this
diff --git a/wifi/1.4/vts/functional/Android.bp b/wifi/1.4/vts/functional/Android.bp
index f86869b..cac8c0b 100644
--- a/wifi/1.4/vts/functional/Android.bp
+++ b/wifi/1.4/vts/functional/Android.bp
@@ -44,6 +44,27 @@
     ],
 }
 
+cc_library_static {
+    name: "VtsHalWifiV1_4TargetTestUtil",
+    defaults: ["VtsHalTargetTestDefaults"],
+    srcs: [
+        "wifi_hidl_test_utils_1_4.cpp",
+    ],
+    export_include_dirs: [
+        ".",
+    ],
+    shared_libs: [
+        "libnativehelper",
+    ],
+    static_libs: [
+        "VtsHalWifiV1_0TargetTestUtil",
+        "android.hardware.wifi@1.0",
+        "android.hardware.wifi@1.3",
+        "android.hardware.wifi@1.4",
+        "libwifi-system-iface",
+    ],
+}
+
 // SoftAP-specific tests, similar to VtsHalWifiApV1_0TargetTest.
 cc_test {
     name: "VtsHalWifiApV1_4TargetTest",
diff --git a/wifi/1.4/vts/functional/wifi_hidl_test_utils_1_4.cpp b/wifi/1.4/vts/functional/wifi_hidl_test_utils_1_4.cpp
new file mode 100644
index 0000000..02e8320
--- /dev/null
+++ b/wifi/1.4/vts/functional/wifi_hidl_test_utils_1_4.cpp
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <VtsHalHidlTargetCallbackBase.h>
+#include <android-base/logging.h>
+
+#undef NAN  // NAN is defined in bionic/libc/include/math.h:38
+
+#include <android/hardware/wifi/1.4/IWifi.h>
+#include <android/hardware/wifi/1.4/IWifiApIface.h>
+#include <android/hardware/wifi/1.4/IWifiChip.h>
+#include <gtest/gtest.h>
+#include <hidl/GtestPrinter.h>
+#include <hidl/ServiceManagement.h>
+
+#include "wifi_hidl_call_util.h"
+#include "wifi_hidl_test_utils.h"
+
+using ::android::sp;
+using ::android::hardware::hidl_string;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::wifi::V1_0::ChipModeId;
+using ::android::hardware::wifi::V1_0::IfaceType;
+using ::android::hardware::wifi::V1_4::IWifiApIface;
+using ::android::hardware::wifi::V1_4::IWifiChip;
+
+sp<IWifiChip> getWifiChip_1_4(const std::string& instance_name) {
+    return IWifiChip::castFrom(getWifiChip(instance_name));
+}
+
+sp<IWifiApIface> getWifiApIface_1_4(const std::string& instance_name) {
+    LOG(INFO) << "getWifiApIface_1_4";
+    ChipModeId mode_id;
+    sp<IWifiChip> wifi_chip_ = getWifiChip_1_4(instance_name);
+    configureChipToSupportIfaceType(wifi_chip_, IfaceType::AP, &mode_id);
+    const auto& status_and_iface = HIDL_INVOKE(wifi_chip_, createApIface);
+    LOG(INFO) << "getWifiApIface_1_4 done to status_and_iface";
+    return IWifiApIface::castFrom(status_and_iface.second);
+}
diff --git a/wifi/1.4/vts/functional/wifi_hidl_test_utils_1_4.h b/wifi/1.4/vts/functional/wifi_hidl_test_utils_1_4.h
new file mode 100644
index 0000000..a2c5815
--- /dev/null
+++ b/wifi/1.4/vts/functional/wifi_hidl_test_utils_1_4.h
@@ -0,0 +1,33 @@
+/*
+ * 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 <android/hardware/wifi/1.4/IWifi.h>
+#include <android/hardware/wifi/1.4/IWifiApIface.h>
+#include <android/hardware/wifi/1.4/IWifiChip.h>
+
+#include <getopt.h>
+
+#include <VtsHalHidlTargetTestEnvBase.h>
+// Helper functions to obtain references to the various HIDL interface objects.
+// Note: We only have a single instance of each of these objects currently.
+// These helper functions should be modified to return vectors if we support
+// multiple instances.
+android::sp<android::hardware::wifi::V1_4::IWifiChip> getWifiChip_1_4(
+        const std::string& instance_name);
+android::sp<android::hardware::wifi::V1_4::IWifiApIface> getWifiApIface_1_4(
+        const std::string& instance_name);
diff --git a/wifi/1.6/default/ringbuffer.cpp b/wifi/1.6/default/ringbuffer.cpp
index 6d4ed84..981bf7b 100644
--- a/wifi/1.6/default/ringbuffer.cpp
+++ b/wifi/1.6/default/ringbuffer.cpp
@@ -26,20 +26,26 @@
 
 Ringbuffer::Ringbuffer(size_t maxSize) : size_(0), maxSize_(maxSize) {}
 
-void Ringbuffer::append(const std::vector<uint8_t>& input) {
+enum Ringbuffer::AppendStatus Ringbuffer::append(const std::vector<uint8_t>& input) {
     if (input.size() == 0) {
-        return;
+        return AppendStatus::FAIL_IP_BUFFER_ZERO;
     }
     if (input.size() > maxSize_) {
         LOG(INFO) << "Oversized message of " << input.size() << " bytes is dropped";
-        return;
+        return AppendStatus::FAIL_IP_BUFFER_EXCEEDED_MAXSIZE;
     }
     data_.push_back(input);
     size_ += input.size() * sizeof(input[0]);
     while (size_ > maxSize_) {
+        if (data_.front().size() <= 0 || data_.front().size() > maxSize_) {
+            LOG(ERROR) << "First buffer in the ring buffer is Invalid. Size: "
+                       << data_.front().size();
+            return AppendStatus::FAIL_RING_BUFFER_CORRUPTED;
+        }
         size_ -= data_.front().size() * sizeof(data_.front()[0]);
         data_.pop_front();
     }
+    return AppendStatus::SUCCESS;
 }
 
 const std::list<std::vector<uint8_t>>& Ringbuffer::getData() const {
diff --git a/wifi/1.6/default/ringbuffer.h b/wifi/1.6/default/ringbuffer.h
index 8571a9f..c6a1e4c 100644
--- a/wifi/1.6/default/ringbuffer.h
+++ b/wifi/1.6/default/ringbuffer.h
@@ -31,11 +31,19 @@
  */
 class Ringbuffer {
   public:
+    // Error codes for the append ring buffer operation
+    enum AppendStatus {
+        SUCCESS,
+        FAIL_GENERIC,
+        FAIL_IP_BUFFER_ZERO,
+        FAIL_IP_BUFFER_EXCEEDED_MAXSIZE,
+        FAIL_RING_BUFFER_CORRUPTED
+    };
     explicit Ringbuffer(size_t maxSize);
 
     // Appends the data buffer and deletes from the front until buffer is
     // within |maxSize_|.
-    void append(const std::vector<uint8_t>& input);
+    enum AppendStatus append(const std::vector<uint8_t>& input);
     const std::list<std::vector<uint8_t>>& getData() const;
     void clear();
 
diff --git a/wifi/1.6/default/wifi_chip.cpp b/wifi/1.6/default/wifi_chip.cpp
index f062409..c7c00b1 100644
--- a/wifi/1.6/default/wifi_chip.cpp
+++ b/wifi/1.6/default/wifi_chip.cpp
@@ -1613,6 +1613,7 @@
                     return;
                 }
                 WifiDebugRingBufferStatus hidl_status;
+                Ringbuffer::AppendStatus appendstatus;
                 if (!hidl_struct_util::convertLegacyDebugRingBufferStatusToHidl(status,
                                                                                 &hidl_status)) {
                     LOG(ERROR) << "Error converting ring buffer status";
@@ -1623,13 +1624,19 @@
                     const auto& target = shared_ptr_this->ringbuffer_map_.find(name);
                     if (target != shared_ptr_this->ringbuffer_map_.end()) {
                         Ringbuffer& cur_buffer = target->second;
-                        cur_buffer.append(data);
+                        appendstatus = cur_buffer.append(data);
                     } else {
                         LOG(ERROR) << "Ringname " << name << " not found";
                         return;
                     }
                     // unique_lock unlocked here
                 }
+                if (appendstatus == Ringbuffer::AppendStatus::FAIL_RING_BUFFER_CORRUPTED) {
+                    LOG(ERROR) << "Ringname " << name << " is corrupted. Clear the ring buffer";
+                    shared_ptr_this->writeRingbufferFilesInternal();
+                    return;
+                }
+
             };
     legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->registerRingBufferCallbackHandler(
             getFirstActiveWlanIfaceName(), on_ring_buffer_data_callback);
@@ -1971,6 +1978,11 @@
             }
             unique_fd file_auto_closer(dump_fd);
             for (const auto& cur_block : cur_buffer.getData()) {
+                if (cur_block.size() <= 0 || cur_block.size() > kMaxBufferSizeBytes) {
+                    PLOG(ERROR) << "Ring buffer: " << item.first
+                                << " is corrupted. Invalid block size: " << cur_block.size();
+                    break;
+                }
                 if (write(dump_fd, cur_block.data(), sizeof(cur_block[0]) * cur_block.size()) ==
                     -1) {
                     PLOG(ERROR) << "Error writing to file";
diff --git a/wifi/hostapd/1.2/vts/functional/Android.bp b/wifi/hostapd/1.2/vts/functional/Android.bp
index 9609da5..26edab5 100644
--- a/wifi/hostapd/1.2/vts/functional/Android.bp
+++ b/wifi/hostapd/1.2/vts/functional/Android.bp
@@ -31,12 +31,17 @@
     ],
     static_libs: [
         "VtsHalWifiV1_0TargetTestUtil",
+        "VtsHalWifiV1_4TargetTestUtil",
         "VtsHalWifiHostapdV1_0TargetTestUtil",
         "android.hardware.wifi.hostapd@1.0",
         "android.hardware.wifi.hostapd@1.1",
         "android.hardware.wifi.hostapd@1.2",
         "android.hardware.wifi.hostapd@1.3",
         "android.hardware.wifi@1.0",
+        "android.hardware.wifi@1.1",
+        "android.hardware.wifi@1.2",
+        "android.hardware.wifi@1.3",
+        "android.hardware.wifi@1.4",
         "libgmock",
         "libwifi-system",
         "libwifi-system-iface",
diff --git a/wifi/hostapd/1.2/vts/functional/hostapd_hidl_test.cpp b/wifi/hostapd/1.2/vts/functional/hostapd_hidl_test.cpp
index c40c582..2fade4d 100644
--- a/wifi/hostapd/1.2/vts/functional/hostapd_hidl_test.cpp
+++ b/wifi/hostapd/1.2/vts/functional/hostapd_hidl_test.cpp
@@ -29,6 +29,7 @@
 
 #include "hostapd_hidl_call_util.h"
 #include "hostapd_hidl_test_utils.h"
+#include "wifi_hidl_test_utils_1_4.h"
 
 using ::android::sp;
 using ::android::hardware::hidl_string;
@@ -39,6 +40,9 @@
 using ::android::hardware::wifi::hostapd::V1_2::Ieee80211ReasonCode;
 using ::android::hardware::wifi::hostapd::V1_2::IHostapd;
 using ::android::hardware::wifi::V1_0::IWifi;
+using ::android::hardware::wifi::V1_0::WifiStatusCode;
+using ::android::hardware::wifi::V1_4::IWifiApIface;
+using ::android::hardware::wifi::V1_4::IWifiChip;
 
 namespace {
 constexpr unsigned char kNwSsid[] = {'t', 'e', 's', 't', '1',
@@ -81,23 +85,25 @@
    protected:
     bool isWpa3SaeSupport_ = false;
     bool isAcsSupport_ = false;
-    std::string getPrimaryWlanIfaceName() {
-        std::array<char, PROPERTY_VALUE_MAX> buffer;
-        auto res = property_get("ro.vendor.wifi.sap.interface", buffer.data(),
-                                nullptr);
-        if (res > 0) return buffer.data();
-        property_get("wifi.interface", buffer.data(), "wlan0");
-        return buffer.data();
+
+    std::string setupApIfaceIfNeededAndGetName() {
+        sp<IWifiApIface> wifi_ap_iface;
+        wifi_ap_iface = getWifiApIface_1_4(wifi_instance_name_);
+        EXPECT_NE(nullptr, wifi_ap_iface.get());
+
+        const auto& status_and_name = HIDL_INVOKE(wifi_ap_iface, getName);
+        EXPECT_EQ(WifiStatusCode::SUCCESS, status_and_name.first.code);
+        return status_and_name.second;
     }
 
-    IHostapd::IfaceParams getIfaceParamsWithoutAcs() {
+    IHostapd::IfaceParams getIfaceParamsWithoutAcs(std::string iface_name) {
         ::android::hardware::wifi::hostapd::V1_0::IHostapd::IfaceParams
             iface_params;
         ::android::hardware::wifi::hostapd::V1_1::IHostapd::IfaceParams
             iface_params_1_1;
         IHostapd::IfaceParams iface_params_1_2;
 
-        iface_params.ifaceName = getPrimaryWlanIfaceName();
+        iface_params.ifaceName = iface_name;
         iface_params.hwModeParams.enable80211N = true;
         iface_params.hwModeParams.enable80211AC = false;
         iface_params.channelParams.enableAcs = false;
@@ -114,9 +120,9 @@
         return iface_params_1_2;
     }
 
-    IHostapd::IfaceParams getIfaceParamsWithAcs() {
+    IHostapd::IfaceParams getIfaceParamsWithAcs(std::string iface_name) {
         // First get the settings for WithoutAcs and then make changes
-        IHostapd::IfaceParams iface_params_1_2 = getIfaceParamsWithoutAcs();
+        IHostapd::IfaceParams iface_params_1_2 = getIfaceParamsWithoutAcs(iface_name);
         iface_params_1_2.V1_1.V1_0.channelParams.enableAcs = true;
         iface_params_1_2.V1_1.V1_0.channelParams.acsShouldExcludeDfs = true;
         iface_params_1_2.V1_1.V1_0.channelParams.channel = 0;
@@ -126,8 +132,8 @@
         return iface_params_1_2;
     }
 
-    IHostapd::IfaceParams getIfaceParamsWithAcsAndFreqRange() {
-        IHostapd::IfaceParams iface_params_1_2 = getIfaceParamsWithAcs();
+    IHostapd::IfaceParams getIfaceParamsWithAcsAndFreqRange(std::string iface_name) {
+        IHostapd::IfaceParams iface_params_1_2 = getIfaceParamsWithAcs(iface_name);
         ::android::hardware::wifi::hostapd::V1_2::IHostapd::AcsFrequencyRange
             acsFrequencyRange;
         acsFrequencyRange.start = 2412;
@@ -141,9 +147,8 @@
         return iface_params_1_2;
     }
 
-    IHostapd::IfaceParams getIfaceParamsWithAcsAndInvalidFreqRange() {
-        IHostapd::IfaceParams iface_params_1_2 =
-            getIfaceParamsWithAcsAndFreqRange();
+    IHostapd::IfaceParams getIfaceParamsWithAcsAndInvalidFreqRange(std::string iface_name) {
+        IHostapd::IfaceParams iface_params_1_2 = getIfaceParamsWithAcsAndFreqRange(iface_name);
         iface_params_1_2.channelParams.acsChannelFreqRangesMhz[0].start = 222;
         iface_params_1_2.channelParams.acsChannelFreqRangesMhz[0].end = 999;
         return iface_params_1_2;
@@ -205,8 +210,8 @@
         return nw_params_1_2;
     }
 
-    IHostapd::IfaceParams getIfaceParamsWithInvalidChannel() {
-        IHostapd::IfaceParams iface_params_1_2 = getIfaceParamsWithoutAcs();
+    IHostapd::IfaceParams getIfaceParamsWithInvalidChannel(std::string iface_name) {
+        IHostapd::IfaceParams iface_params_1_2 = getIfaceParamsWithoutAcs(iface_name);
         iface_params_1_2.V1_1.V1_0.channelParams.channel = kIfaceInvalidChannel;
         return iface_params_1_2;
     }
@@ -231,8 +236,9 @@
     if (!isAcsSupport_) GTEST_SKIP() << "Missing ACS support";
     if (is_1_3(hostapd_))
         GTEST_SKIP() << "Ignore addAccessPoint_1_2 on hostapd 1_3";
-    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2,
-                              getIfaceParamsWithAcs(), getPskNwParams());
+    std::string ifname = setupApIfaceIfNeededAndGetName();
+    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithAcs(ifname),
+                              getPskNwParams());
     EXPECT_EQ(HostapdStatusCode::SUCCESS, status.code);
 }
 
@@ -244,9 +250,9 @@
     if (!isAcsSupport_) GTEST_SKIP() << "Missing ACS support";
     if (is_1_3(hostapd_))
         GTEST_SKIP() << "Ignore addAccessPoint_1_2 on hostapd 1_3";
-    auto status =
-        HIDL_INVOKE(hostapd_, addAccessPoint_1_2,
-                    getIfaceParamsWithAcsAndFreqRange(), getPskNwParams());
+    std::string ifname = setupApIfaceIfNeededAndGetName();
+    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2,
+                              getIfaceParamsWithAcsAndFreqRange(ifname), getPskNwParams());
     EXPECT_EQ(HostapdStatusCode::SUCCESS, status.code);
 }
 
@@ -258,9 +264,9 @@
     if (!isAcsSupport_) GTEST_SKIP() << "Missing ACS support";
     if (is_1_3(hostapd_))
         GTEST_SKIP() << "Ignore addAccessPoint_1_2 on hostapd 1_3";
+    std::string ifname = setupApIfaceIfNeededAndGetName();
     auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2,
-                              getIfaceParamsWithAcsAndInvalidFreqRange(),
-                              getPskNwParams());
+                              getIfaceParamsWithAcsAndInvalidFreqRange(ifname), getPskNwParams());
     EXPECT_NE(HostapdStatusCode::SUCCESS, status.code);
 }
 
@@ -272,8 +278,9 @@
     if (!isAcsSupport_) GTEST_SKIP() << "Missing ACS support";
     if (is_1_3(hostapd_))
         GTEST_SKIP() << "Ignore addAccessPoint_1_2 on hostapd 1_3";
-    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2,
-                              getIfaceParamsWithAcs(), getOpenNwParams());
+    std::string ifname = setupApIfaceIfNeededAndGetName();
+    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithAcs(ifname),
+                              getOpenNwParams());
     EXPECT_EQ(HostapdStatusCode::SUCCESS, status.code);
 }
 
@@ -284,8 +291,9 @@
 TEST_P(HostapdHidlTest, AddPskAccessPointWithoutAcs) {
     if (is_1_3(hostapd_))
         GTEST_SKIP() << "Ignore addAccessPoint_1_2 on hostapd 1_3";
-    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2,
-                              getIfaceParamsWithoutAcs(), getPskNwParams());
+    std::string ifname = setupApIfaceIfNeededAndGetName();
+    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithoutAcs(ifname),
+                              getPskNwParams());
     EXPECT_EQ(HostapdStatusCode::SUCCESS, status.code);
 }
 
@@ -296,8 +304,9 @@
 TEST_P(HostapdHidlTest, AddOpenAccessPointWithoutAcs) {
     if (is_1_3(hostapd_))
         GTEST_SKIP() << "Ignore addAccessPoint_1_2 on hostapd 1_3";
-    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2,
-                              getIfaceParamsWithoutAcs(), getOpenNwParams());
+    std::string ifname = setupApIfaceIfNeededAndGetName();
+    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithoutAcs(ifname),
+                              getOpenNwParams());
     EXPECT_EQ(HostapdStatusCode::SUCCESS, status.code);
 }
 
@@ -309,9 +318,9 @@
     if (!isWpa3SaeSupport_) GTEST_SKIP() << "Missing SAE support";
     if (is_1_3(hostapd_))
         GTEST_SKIP() << "Ignore addAccessPoint_1_2 on hostapd 1_3";
-    auto status =
-        HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithoutAcs(),
-                    getSaeTransitionNwParams());
+    std::string ifname = setupApIfaceIfNeededAndGetName();
+    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithoutAcs(ifname),
+                              getSaeTransitionNwParams());
     EXPECT_EQ(HostapdStatusCode::SUCCESS, status.code);
 }
 
@@ -323,8 +332,9 @@
     if (!isWpa3SaeSupport_) GTEST_SKIP() << "Missing SAE support";
     if (is_1_3(hostapd_))
         GTEST_SKIP() << "Ignore addAccessPoint_1_2 on hostapd 1_3";
-    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2,
-                              getIfaceParamsWithoutAcs(), getSaeNwParams());
+    std::string ifname = setupApIfaceIfNeededAndGetName();
+    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithoutAcs(ifname),
+                              getSaeNwParams());
     EXPECT_EQ(HostapdStatusCode::SUCCESS, status.code);
 }
 
@@ -336,11 +346,11 @@
     if (!isAcsSupport_) GTEST_SKIP() << "Missing ACS support";
     if (is_1_3(hostapd_))
         GTEST_SKIP() << "Ignore addAccessPoint_1_2 on hostapd 1_3";
-    auto status_1_2 = HIDL_INVOKE(hostapd_, addAccessPoint_1_2,
-                                  getIfaceParamsWithAcs(), getPskNwParams());
+    std::string ifname = setupApIfaceIfNeededAndGetName();
+    auto status_1_2 = HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithAcs(ifname),
+                                  getPskNwParams());
     EXPECT_EQ(HostapdStatusCode::SUCCESS, status_1_2.code);
-    auto status =
-        HIDL_INVOKE(hostapd_, removeAccessPoint, getPrimaryWlanIfaceName());
+    auto status = HIDL_INVOKE(hostapd_, removeAccessPoint, ifname);
     EXPECT_EQ(
         android::hardware::wifi::hostapd::V1_0::HostapdStatusCode::SUCCESS,
         status.code);
@@ -353,11 +363,11 @@
 TEST_P(HostapdHidlTest, RemoveAccessPointWithoutAcs) {
     if (is_1_3(hostapd_))
         GTEST_SKIP() << "Ignore addAccessPoint_1_2 on hostapd 1_3";
-    auto status_1_2 = HIDL_INVOKE(hostapd_, addAccessPoint_1_2,
-                                  getIfaceParamsWithoutAcs(), getPskNwParams());
+    std::string ifname = setupApIfaceIfNeededAndGetName();
+    auto status_1_2 = HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithoutAcs(ifname),
+                                  getPskNwParams());
     EXPECT_EQ(HostapdStatusCode::SUCCESS, status_1_2.code);
-    auto status =
-        HIDL_INVOKE(hostapd_, removeAccessPoint, getPrimaryWlanIfaceName());
+    auto status = HIDL_INVOKE(hostapd_, removeAccessPoint, ifname);
     EXPECT_EQ(
         android::hardware::wifi::hostapd::V1_0::HostapdStatusCode::SUCCESS,
         status.code);
@@ -370,9 +380,9 @@
 TEST_P(HostapdHidlTest, AddPskAccessPointWithInvalidChannel) {
     if (is_1_3(hostapd_))
         GTEST_SKIP() << "Ignore addAccessPoint_1_2 on hostapd 1_3";
-    auto status =
-        HIDL_INVOKE(hostapd_, addAccessPoint_1_2,
-                    getIfaceParamsWithInvalidChannel(), getPskNwParams());
+    std::string ifname = setupApIfaceIfNeededAndGetName();
+    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2,
+                              getIfaceParamsWithInvalidChannel(ifname), getPskNwParams());
     EXPECT_NE(HostapdStatusCode::SUCCESS, status.code);
 }
 
@@ -383,9 +393,9 @@
 TEST_P(HostapdHidlTest, AddInvalidPskAccessPointWithoutAcs) {
     if (is_1_3(hostapd_))
         GTEST_SKIP() << "Ignore addAccessPoint_1_2 on hostapd 1_3";
-    auto status =
-        HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithoutAcs(),
-                    getInvalidPskNwParams());
+    std::string ifname = setupApIfaceIfNeededAndGetName();
+    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithoutAcs(ifname),
+                              getInvalidPskNwParams());
     EXPECT_NE(HostapdStatusCode::SUCCESS, status.code);
 }
 
@@ -397,9 +407,9 @@
     if (!isWpa3SaeSupport_) GTEST_SKIP() << "Missing SAE support";
     if (is_1_3(hostapd_))
         GTEST_SKIP() << "Ignore addAccessPoint_1_2 on hostapd 1_3";
-    auto status =
-        HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithoutAcs(),
-                    getInvalidSaeTransitionNwParams());
+    std::string ifname = setupApIfaceIfNeededAndGetName();
+    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithoutAcs(ifname),
+                              getInvalidSaeTransitionNwParams());
     EXPECT_NE(HostapdStatusCode::SUCCESS, status.code);
 }
 
@@ -411,9 +421,9 @@
     if (!isWpa3SaeSupport_) GTEST_SKIP() << "Missing SAE support";
     if (is_1_3(hostapd_))
         GTEST_SKIP() << "Ignore addAccessPoint_1_2 on hostapd 1_3";
-    auto status =
-        HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithoutAcs(),
-                    getInvalidSaeNwParams());
+    std::string ifname = setupApIfaceIfNeededAndGetName();
+    auto status = HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithoutAcs(ifname),
+                              getInvalidSaeNwParams());
     EXPECT_NE(HostapdStatusCode::SUCCESS, status.code);
 }
 
@@ -422,9 +432,9 @@
  * when hotspot interface doesn't init..
  */
 TEST_P(HostapdHidlTest, DisconnectClientWhenIfaceNotAvailable) {
-    auto status =
-        HIDL_INVOKE(hostapd_, forceClientDisconnect, getPrimaryWlanIfaceName(),
-                    kTestZeroMacAddr, kTestDisconnectReasonCode);
+    std::string ifname = setupApIfaceIfNeededAndGetName();
+    auto status = HIDL_INVOKE(hostapd_, forceClientDisconnect, ifname, kTestZeroMacAddr,
+                              kTestDisconnectReasonCode);
     EXPECT_EQ(HostapdStatusCode::FAILURE_IFACE_UNKNOWN, status.code);
 }
 
@@ -435,14 +445,13 @@
 TEST_P(HostapdHidlTest, DisconnectClientWhenIfacAvailable) {
     if (is_1_3(hostapd_))
         GTEST_SKIP() << "Ignore addAccessPoint_1_2 on hostapd 1_3";
-    auto status_1_2 =
-        HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithoutAcs(),
-                    getOpenNwParams());
+    std::string ifname = setupApIfaceIfNeededAndGetName();
+    auto status_1_2 = HIDL_INVOKE(hostapd_, addAccessPoint_1_2, getIfaceParamsWithoutAcs(ifname),
+                                  getOpenNwParams());
     EXPECT_EQ(HostapdStatusCode::SUCCESS, status_1_2.code);
 
-    status_1_2 =
-        HIDL_INVOKE(hostapd_, forceClientDisconnect, getPrimaryWlanIfaceName(),
-                    kTestZeroMacAddr, kTestDisconnectReasonCode);
+    status_1_2 = HIDL_INVOKE(hostapd_, forceClientDisconnect, ifname, kTestZeroMacAddr,
+                             kTestDisconnectReasonCode);
     EXPECT_EQ(HostapdStatusCode::FAILURE_CLIENT_UNKNOWN, status_1_2.code);
 }
 
diff --git a/wifi/supplicant/1.0/vts/functional/supplicant_hidl_test.cpp b/wifi/supplicant/1.0/vts/functional/supplicant_hidl_test.cpp
index eabbf1b..da3ff3a 100644
--- a/wifi/supplicant/1.0/vts/functional/supplicant_hidl_test.cpp
+++ b/wifi/supplicant/1.0/vts/functional/supplicant_hidl_test.cpp
@@ -38,11 +38,12 @@
     : public ::testing::TestWithParam<std::tuple<std::string, std::string>> {
    public:
     virtual void SetUp() override {
-        // Stop Wi-Fi
-        ASSERT_TRUE(stopWifiFramework());  // stop & wait for wifi to shutdown.
-
         wifi_instance_name_ = std::get<0>(GetParam());
         supplicant_instance_name_ = std::get<1>(GetParam());
+
+        // Stop & wait for wifi to shutdown.
+        ASSERT_TRUE(stopWifiFramework(wifi_instance_name_));
+
         std::system("/system/bin/start");
         ASSERT_TRUE(waitForFrameworkReady());
         isP2pOn_ =
diff --git a/wifi/supplicant/1.0/vts/functional/supplicant_hidl_test_utils.cpp b/wifi/supplicant/1.0/vts/functional/supplicant_hidl_test_utils.cpp
index 086166a..6760663 100644
--- a/wifi/supplicant/1.0/vts/functional/supplicant_hidl_test_utils.cpp
+++ b/wifi/supplicant/1.0/vts/functional/supplicant_hidl_test_utils.cpp
@@ -28,26 +28,42 @@
 
 using ::android::sp;
 using ::android::hardware::configureRpcThreadpool;
-using ::android::hardware::joinRpcThreadpool;
 using ::android::hardware::hidl_string;
 using ::android::hardware::hidl_vec;
+using ::android::hardware::joinRpcThreadpool;
 using ::android::hardware::Return;
 using ::android::hardware::Void;
-using ::android::hardware::wifi::V1_0::ChipModeId;
-using ::android::hardware::wifi::V1_0::IWifiChip;
+using ::android::hardware::wifi::supplicant::V1_0::IfaceType;
 using ::android::hardware::wifi::supplicant::V1_0::ISupplicant;
 using ::android::hardware::wifi::supplicant::V1_0::ISupplicantIface;
 using ::android::hardware::wifi::supplicant::V1_0::ISupplicantNetwork;
+using ::android::hardware::wifi::supplicant::V1_0::ISupplicantP2pIface;
 using ::android::hardware::wifi::supplicant::V1_0::ISupplicantStaIface;
 using ::android::hardware::wifi::supplicant::V1_0::ISupplicantStaNetwork;
-using ::android::hardware::wifi::supplicant::V1_0::ISupplicantP2pIface;
-using ::android::hardware::wifi::supplicant::V1_0::IfaceType;
 using ::android::hardware::wifi::supplicant::V1_0::SupplicantStatus;
 using ::android::hardware::wifi::supplicant::V1_0::SupplicantStatusCode;
+using ::android::hardware::wifi::V1_0::ChipModeId;
+using ::android::hardware::wifi::V1_0::IWifi;
+using ::android::hardware::wifi::V1_0::IWifiChip;
 using ::android::wifi_system::InterfaceTool;
 using ::android::wifi_system::SupplicantManager;
 
 namespace {
+
+bool waitForWifiHalStop(const std::string& wifi_instance_name) {
+    sp<IWifi> wifi = getWifi(wifi_instance_name);
+    int count = 50; /* wait at most 5 seconds for completion */
+    while (count-- > 0) {
+        if (wifi != nullptr && !wifi->isStarted()) {
+            return true;
+        }
+        usleep(100000);
+        wifi = getWifi(wifi_instance_name);
+    }
+    LOG(ERROR) << "Wifi HAL was not stopped";
+    return false;
+}
+
 bool waitForSupplicantState(bool is_running) {
     SupplicantManager supplicant_manager;
     int count = 50; /* wait at most 5 seconds for completion */
@@ -113,10 +129,10 @@
     return waitForSupplicantStart();  // wait for wifi to start.
 }
 
-bool stopWifiFramework() {
+bool stopWifiFramework(const std::string& wifi_instance_name) {
     std::system("svc wifi disable");
     std::system("cmd wifi set-scan-always-available disabled");
-    return waitForSupplicantStop();  // wait for wifi to shutdown.
+    return waitForSupplicantStop() && waitForWifiHalStop(wifi_instance_name);
 }
 
 void stopSupplicant() { stopSupplicant(""); }
diff --git a/wifi/supplicant/1.0/vts/functional/supplicant_hidl_test_utils.h b/wifi/supplicant/1.0/vts/functional/supplicant_hidl_test_utils.h
index 7228623..2198d7c 100644
--- a/wifi/supplicant/1.0/vts/functional/supplicant_hidl_test_utils.h
+++ b/wifi/supplicant/1.0/vts/functional/supplicant_hidl_test_utils.h
@@ -33,7 +33,7 @@
 bool startWifiFramework();
 
 // Used to stop the android wifi framework before every test.
-bool stopWifiFramework();
+bool stopWifiFramework(const std::string& wifi_instance_name);
 
 void stopSupplicant(const std::string& wifi_instance_name);
 // Used to configure the chip, driver and start wpa_supplicant before every
@@ -77,12 +77,13 @@
     : public ::testing::TestWithParam<std::tuple<std::string, std::string>> {
    public:
     virtual void SetUp() override {
-        // Stop Wi-Fi
-        ASSERT_TRUE(stopWifiFramework());  // stop & wait for wifi to shutdown.
-
-        // should always be v1.0 wifi
-        wifi_v1_0_instance_name_ = std::get<0>(GetParam());
+        wifi_v1_0_instance_name_ =
+            std::get<0>(GetParam());  // should always be v1.0 wifi
         supplicant_instance_name_ = std::get<1>(GetParam());
+
+        // Stop & wait for wifi to shutdown.
+        ASSERT_TRUE(stopWifiFramework(wifi_v1_0_instance_name_));
+
         std::system("/system/bin/start");
         ASSERT_TRUE(waitForFrameworkReady());
         isP2pOn_ =
diff --git a/wifi/supplicant/aidl/vts/functional/supplicant_test_utils.h b/wifi/supplicant/aidl/vts/functional/supplicant_test_utils.h
index 17e0394..31042a2 100644
--- a/wifi/supplicant/aidl/vts/functional/supplicant_test_utils.h
+++ b/wifi/supplicant/aidl/vts/functional/supplicant_test_utils.h
@@ -78,7 +78,7 @@
 void stopSupplicantService() { stopSupplicant(getWifiInstanceName()); }
 
 void initializeService() {
-    ASSERT_TRUE(stopWifiFramework());
+    ASSERT_TRUE(stopWifiFramework(getWifiInstanceName()));
     std::system("/system/bin/start");
     ASSERT_TRUE(waitForFrameworkReady());
     stopSupplicantService();