Merge "graphics: add graphics common 1.1 HAL with new pixel formats and usages."
diff --git a/audio/2.0/default/Android.mk b/audio/2.0/default/Android.mk
index aa25077..7f42abe 100644
--- a/audio/2.0/default/Android.mk
+++ b/audio/2.0/default/Android.mk
@@ -78,7 +78,7 @@
     android.hardware.audio@2.0 \
     android.hardware.audio.common@2.0 \
     android.hardware.audio.effect@2.0 \
-    android.hardware.soundtrigger@2.0 \
+    android.hardware.soundtrigger@2.1 \
     android.hardware.broadcastradio@1.0 \
     android.hardware.broadcastradio@1.1
 
diff --git a/audio/2.0/default/service.cpp b/audio/2.0/default/service.cpp
index a215108..4763c70 100644
--- a/audio/2.0/default/service.cpp
+++ b/audio/2.0/default/service.cpp
@@ -16,11 +16,11 @@
 
 #define LOG_TAG "audiohalservice"
 
-#include <hidl/HidlTransportSupport.h>
-#include <hidl/LegacySupport.h>
 #include <android/hardware/audio/2.0/IDevicesFactory.h>
 #include <android/hardware/audio/effect/2.0/IEffectsFactory.h>
-#include <android/hardware/soundtrigger/2.0/ISoundTriggerHw.h>
+#include <android/hardware/soundtrigger/2.1/ISoundTriggerHw.h>
+#include <hidl/HidlTransportSupport.h>
+#include <hidl/LegacySupport.h>
 
 using android::hardware::configureRpcThreadpool;
 using android::hardware::joinRpcThreadpool;
@@ -28,7 +28,7 @@
 
 using android::hardware::audio::effect::V2_0::IEffectsFactory;
 using android::hardware::audio::V2_0::IDevicesFactory;
-using android::hardware::soundtrigger::V2_0::ISoundTriggerHw;
+using android::hardware::soundtrigger::V2_1::ISoundTriggerHw;
 using android::hardware::registerPassthroughServiceImplementation;
 
 using android::OK;
diff --git a/broadcastradio/2.0/ITunerSession.hal b/broadcastradio/2.0/ITunerSession.hal
index a58fa62..e891a23 100644
--- a/broadcastradio/2.0/ITunerSession.hal
+++ b/broadcastradio/2.0/ITunerSession.hal
@@ -113,12 +113,12 @@
      *                NOT_SUPPORTED if the flag is not supported at all.
      * @return value The current value of the flag, if result is OK.
      */
-    getConfigFlag(ConfigFlag flag) generates (Result result, bool value);
+    isConfigFlagSet(ConfigFlag flag) generates (Result result, bool value);
 
     /**
      * Sets the config flag.
      *
-     * The success/failure result must be consistent with getConfigFlag.
+     * The success/failure result must be consistent with isConfigFlagSet.
      *
      * @param flag Flag to set.
      * @param value The new value of a given flag.
diff --git a/broadcastradio/2.0/default/BroadcastRadio.cpp b/broadcastradio/2.0/default/BroadcastRadio.cpp
index aa5afad..0148fec 100644
--- a/broadcastradio/2.0/default/BroadcastRadio.cpp
+++ b/broadcastradio/2.0/default/BroadcastRadio.cpp
@@ -112,6 +112,12 @@
 Return<void> BroadcastRadio::openSession(const sp<ITunerCallback>& callback,
                                          openSession_cb _hidl_cb) {
     ALOGV("%s", __func__);
+
+    /* For the needs of default implementation it's fine to instantiate new session object
+     * out of the lock scope. If your implementation needs it, use reentrant lock.
+     */
+    sp<TunerSession> newSession = new TunerSession(*this, callback);
+
     lock_guard<mutex> lk(mMut);
 
     auto oldSession = mSession.promote();
@@ -121,7 +127,6 @@
         mSession = nullptr;
     }
 
-    sp<TunerSession> newSession = new TunerSession(*this, callback);
     mSession = newSession;
 
     _hidl_cb(Result::OK, newSession);
diff --git a/broadcastradio/2.0/default/TunerSession.cpp b/broadcastradio/2.0/default/TunerSession.cpp
index 3166d86..56a3508 100644
--- a/broadcastradio/2.0/default/TunerSession.cpp
+++ b/broadcastradio/2.0/default/TunerSession.cpp
@@ -50,7 +50,12 @@
 }  // namespace delay
 
 TunerSession::TunerSession(BroadcastRadio& module, const sp<ITunerCallback>& callback)
-    : mCallback(callback), mModule(module) {}
+    : mCallback(callback), mModule(module) {
+    auto&& ranges = module.getAmFmConfig().ranges;
+    if (ranges.size() > 0) {
+        tuneInternalLocked(utils::make_selector_amfm(ranges[0].lowerBound));
+    }
+}
 
 // makes ProgramInfo that points to no program
 static ProgramInfo makeDummyProgramInfo(const ProgramSelector& selector) {
@@ -63,6 +68,8 @@
 }
 
 void TunerSession::tuneInternalLocked(const ProgramSelector& sel) {
+    ALOGV("%s(%s)", __func__, toString(sel).c_str());
+
     VirtualProgram virtualProgram;
     ProgramInfo programInfo;
     if (virtualRadio().getProgram(sel, virtualProgram)) {
@@ -100,6 +107,8 @@
         return Result::INVALID_ARGUMENTS;
     }
 
+    cancelLocked();
+
     mIsTuneCompleted = false;
     auto task = [this, sel]() {
         lock_guard<mutex> lk(mMut);
@@ -115,6 +124,8 @@
     lock_guard<mutex> lk(mMut);
     if (mIsClosed) return Result::INVALID_STATE;
 
+    cancelLocked();
+
     auto list = virtualRadio().getProgramList();
 
     if (list.empty()) {
@@ -166,13 +177,13 @@
     lock_guard<mutex> lk(mMut);
     if (mIsClosed) return Result::INVALID_STATE;
 
+    cancelLocked();
+
     if (!utils::hasId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY)) {
         ALOGE("Can't step in anything else than AM/FM");
         return Result::NOT_SUPPORTED;
     }
 
-    mIsTuneCompleted = false;
-
     auto stepTo = utils::getId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY);
     auto range = getAmFmRangeLocked();
     if (!range) {
@@ -188,6 +199,7 @@
     if (stepTo > range->upperBound) stepTo = range->lowerBound;
     if (stepTo < range->lowerBound) stepTo = range->upperBound;
 
+    mIsTuneCompleted = false;
     auto task = [this, stepTo]() {
         ALOGI("Performing step to %s", std::to_string(stepTo).c_str());
 
@@ -200,12 +212,22 @@
     return Result::OK;
 }
 
+void TunerSession::cancelLocked() {
+    ALOGV("%s", __func__);
+
+    mThread.cancelAll();
+    if (utils::getType(mCurrentProgram.primaryId) != IdentifierType::INVALID) {
+        mIsTuneCompleted = true;
+    }
+}
+
 Return<void> TunerSession::cancel() {
     ALOGV("%s", __func__);
     lock_guard<mutex> lk(mMut);
     if (mIsClosed) return {};
 
-    mThread.cancelAll();
+    cancelLocked();
+
     return {};
 }
 
@@ -241,7 +263,7 @@
     return {};
 }
 
-Return<void> TunerSession::getConfigFlag(ConfigFlag flag, getConfigFlag_cb _hidl_cb) {
+Return<void> TunerSession::isConfigFlagSet(ConfigFlag flag, isConfigFlagSet_cb _hidl_cb) {
     ALOGV("%s(%s)", __func__, toString(flag).c_str());
 
     _hidl_cb(Result::NOT_SUPPORTED, false);
@@ -281,7 +303,10 @@
 }
 
 std::optional<AmFmBandRange> TunerSession::getAmFmRangeLocked() const {
-    if (!mIsTuneCompleted) return {};
+    if (!mIsTuneCompleted) {
+        ALOGW("tune operation in process");
+        return {};
+    }
     if (!utils::hasId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY)) return {};
 
     auto freq = utils::getId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY);
diff --git a/broadcastradio/2.0/default/TunerSession.h b/broadcastradio/2.0/default/TunerSession.h
index 5d27b1e..bf7c607 100644
--- a/broadcastradio/2.0/default/TunerSession.h
+++ b/broadcastradio/2.0/default/TunerSession.h
@@ -42,7 +42,7 @@
     virtual Return<void> cancel() override;
     virtual Return<Result> startProgramListUpdates(const ProgramFilter& filter);
     virtual Return<void> stopProgramListUpdates();
-    virtual Return<void> getConfigFlag(ConfigFlag flag, getConfigFlag_cb _hidl_cb);
+    virtual Return<void> isConfigFlagSet(ConfigFlag flag, isConfigFlagSet_cb _hidl_cb);
     virtual Return<Result> setConfigFlag(ConfigFlag flag, bool value);
     virtual Return<void> setParameters(const hidl_vec<VendorKeyValue>& parameters,
                                        setParameters_cb _hidl_cb) override;
@@ -63,6 +63,7 @@
     bool mIsTuneCompleted = false;
     ProgramSelector mCurrentProgram = {};
 
+    void cancelLocked();
     void tuneInternalLocked(const ProgramSelector& sel);
     const VirtualRadio& virtualRadio() const;
     const BroadcastRadio& module() const;
diff --git a/broadcastradio/2.0/types.hal b/broadcastradio/2.0/types.hal
index 1fd3715..9fd0738 100644
--- a/broadcastradio/2.0/types.hal
+++ b/broadcastradio/2.0/types.hal
@@ -40,7 +40,7 @@
 };
 
 /**
- * Configuration flags to be used with getConfigFlag and setConfigFlag methods
+ * Configuration flags to be used with isConfigFlagSet and setConfigFlag methods
  * of ITunerSession.
  */
 enum ConfigFlag : uint32_t {
@@ -215,7 +215,9 @@
     /**
      * Channel name, i.e. 5A, 7B.
      *
-     * It must match the following regular expression: /^[A-Z0-9]{2,5}$/.
+     * It must match the following regular expression:
+     * /^[A-Z0-9][A-Z0-9 ]{0,5}[A-Z0-9]$/ (2-7 uppercase alphanumeric characters
+     * without spaces allowed at the beginning nor end).
      */
     string label;
 
diff --git a/broadcastradio/2.0/vts/functional/VtsHalBroadcastradioV2_0TargetTest.cpp b/broadcastradio/2.0/vts/functional/VtsHalBroadcastradioV2_0TargetTest.cpp
index 8d9d622..37095d4 100644
--- a/broadcastradio/2.0/vts/functional/VtsHalBroadcastradioV2_0TargetTest.cpp
+++ b/broadcastradio/2.0/vts/functional/VtsHalBroadcastradioV2_0TargetTest.cpp
@@ -15,6 +15,8 @@
  */
 
 #define LOG_TAG "BcRadio.vts"
+#define LOG_NDEBUG 0
+#define EGMOCK_VERBOSE 1
 
 #include <VtsHalHidlTargetTestBase.h>
 #include <android-base/logging.h>
@@ -113,7 +115,15 @@
     std::cout << "[  SKIPPED ] " << msg << std::endl;
 }
 
+MATCHER_P(InfoHasId, id,
+          std::string(negation ? "does not contain" : "contains") + " " + toString(id)) {
+    auto ids = utils::getAllIds(arg.selector, utils::getType(id));
+    return ids.end() != find(ids.begin(), ids.end(), id.value);
+}
+
 TunerCallbackMock::TunerCallbackMock() {
+    EXPECT_TIMEOUT_CALL(*this, onCurrentProgramInfoChanged, _).Times(AnyNumber());
+
     // we expect the antenna is connected through the whole test
     EXPECT_CALL(*this, onAntennaStateChange(false)).Times(0);
 }
@@ -332,11 +342,13 @@
     }
     ASSERT_EQ(Result::OK, halResult);
 
-    std::regex re("^[A-Z0-9]{2,5}$");
+    std::regex re("^[A-Z0-9][A-Z0-9 ]{0,5}[A-Z0-9]$");
     // double-check correctness of the test
     ASSERT_TRUE(std::regex_match("5A", re));
     ASSERT_FALSE(std::regex_match("5a", re));
-    ASSERT_FALSE(std::regex_match("123ABC", re));
+    ASSERT_FALSE(std::regex_match("1234ABCD", re));
+    ASSERT_TRUE(std::regex_match("CN 12D", re));
+    ASSERT_FALSE(std::regex_match(" 5A", re));
 
     for (auto&& entry : config) {
         EXPECT_TRUE(std::regex_match(std::string(entry.label), re));
@@ -362,9 +374,19 @@
     uint64_t freq = 100100;  // 100.1 FM
     auto sel = make_selector_amfm(freq);
 
+    /* TODO(b/69958777): there is a race condition between tune() and onCurrentProgramInfoChanged
+     * callback setting infoCb, because egmock cannot distinguish calls with different matchers
+     * (there is one here and one in callback constructor).
+     *
+     * This sleep workaround will fix default implementation, but the real HW tests will still be
+     * flaky. We probably need to implement egmock alternative based on actions.
+     */
+    std::this_thread::sleep_for(100ms);
+
     // try tuning
     ProgramInfo infoCb = {};
-    EXPECT_TIMEOUT_CALL(*mCallback, onCurrentProgramInfoChanged, _)
+    EXPECT_TIMEOUT_CALL(*mCallback, onCurrentProgramInfoChanged,
+                        InfoHasId(utils::make_identifier(IdentifierType::AMFM_FREQUENCY, freq)))
         .Times(AnyNumber())
         .WillOnce(DoAll(SaveArg<0>(&infoCb), testing::Return(ByMove(Void()))));
     auto result = mSession->tune(sel);
@@ -379,6 +401,8 @@
     EXPECT_EQ(Result::OK, result);
     EXPECT_TIMEOUT_CALL_WAIT(*mCallback, onCurrentProgramInfoChanged, timeout::tune);
 
+    ALOGD("current program info: %s", toString(infoCb).c_str());
+
     // it should tune exactly to what was requested
     auto freqs = utils::getAllIds(infoCb.selector, IdentifierType::AMFM_FREQUENCY);
     EXPECT_NE(freqs.end(), find(freqs.begin(), freqs.end(), freq));
@@ -442,6 +466,9 @@
 TEST_F(BroadcastRadioHalTest, Scan) {
     ASSERT_TRUE(openSession());
 
+    // TODO(b/69958777): see FmTune workaround
+    std::this_thread::sleep_for(100ms);
+
     EXPECT_TIMEOUT_CALL(*mCallback, onCurrentProgramInfoChanged, _);
     auto result = mSession->scan(true /* up */, true /* skip subchannel */);
     EXPECT_EQ(Result::OK, result);
@@ -464,9 +491,15 @@
 TEST_F(BroadcastRadioHalTest, Step) {
     ASSERT_TRUE(openSession());
 
+    // TODO(b/69958777): see FmTune workaround
+    std::this_thread::sleep_for(100ms);
+
     EXPECT_TIMEOUT_CALL(*mCallback, onCurrentProgramInfoChanged, _).Times(AnyNumber());
     auto result = mSession->step(true /* up */);
-    if (result == Result::NOT_SUPPORTED) return;
+    if (result == Result::NOT_SUPPORTED) {
+        printSkipped("step not supported");
+        return;
+    }
     EXPECT_EQ(Result::OK, result);
     EXPECT_TIMEOUT_CALL_WAIT(*mCallback, onCurrentProgramInfoChanged, timeout::tune);
 
@@ -584,16 +617,16 @@
  * Test getting config flags.
  *
  * Verifies that:
- * - getConfigFlag either succeeds or ends with NOT_SUPPORTED or INVALID_STATE;
+ * - isConfigFlagSet either succeeds or ends with NOT_SUPPORTED or INVALID_STATE;
  * - call success or failure is consistent with setConfigFlag.
  */
-TEST_F(BroadcastRadioHalTest, GetConfigFlags) {
+TEST_F(BroadcastRadioHalTest, FetchConfigFlags) {
     ASSERT_TRUE(openSession());
 
     for (auto flag : gConfigFlagValues) {
         auto halResult = Result::UNKNOWN_ERROR;
         auto cb = [&](Result result, bool) { halResult = result; };
-        auto hidlResult = mSession->getConfigFlag(flag, cb);
+        auto hidlResult = mSession->isConfigFlagSet(flag, cb);
         EXPECT_TRUE(hidlResult.isOk());
 
         if (halResult != Result::NOT_SUPPORTED && halResult != Result::INVALID_STATE) {
@@ -613,7 +646,7 @@
  *
  * Verifies that:
  * - setConfigFlag either succeeds or ends with NOT_SUPPORTED or INVALID_STATE;
- * - getConfigFlag reflects the state requested immediately after the set call.
+ * - isConfigFlagSet reflects the state requested immediately after the set call.
  */
 TEST_F(BroadcastRadioHalTest, SetConfigFlags) {
     ASSERT_TRUE(openSession());
@@ -625,7 +658,7 @@
             halResult = result;
             gotValue = value;
         };
-        auto hidlResult = mSession->getConfigFlag(flag, cb);
+        auto hidlResult = mSession->isConfigFlagSet(flag, cb);
         EXPECT_TRUE(hidlResult.isOk());
         EXPECT_EQ(Result::OK, halResult);
         return gotValue;
diff --git a/broadcastradio/common/vts/utils/include/broadcastradio-vts-utils/mock-timeout.h b/broadcastradio/common/vts/utils/include/broadcastradio-vts-utils/mock-timeout.h
index 12453bb..1f716f1 100644
--- a/broadcastradio/common/vts/utils/include/broadcastradio-vts-utils/mock-timeout.h
+++ b/broadcastradio/common/vts/utils/include/broadcastradio-vts-utils/mock-timeout.h
@@ -13,12 +13,27 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#ifndef ANDROID_HARDWARE_BROADCASTRADIO_V1_1_MOCK_TIMEOUT
-#define ANDROID_HARDWARE_BROADCASTRADIO_V1_1_MOCK_TIMEOUT
+#ifndef ANDROID_HARDWARE_BROADCASTRADIO_VTS_MOCK_TIMEOUT
+#define ANDROID_HARDWARE_BROADCASTRADIO_VTS_MOCK_TIMEOUT
 
 #include <gmock/gmock.h>
 #include <thread>
 
+#ifndef EGMOCK_VERBOSE
+#define EGMOCK_VERBOSE 0
+#endif
+
+/**
+ * Print log message.
+ *
+ * INTERNAL IMPLEMENTATION - don't use in user code.
+ */
+#if EGMOCK_VERBOSE
+#define EGMOCK_LOG_(...) ALOGV("egmock: " __VA_ARGS__)
+#else
+#define EGMOCK_LOG_(...)
+#endif
+
 /**
  * Common helper objects for gmock timeout extension.
  *
@@ -61,6 +76,7 @@
     auto invokeMock = [&]() { return egmock_##Method(__VA_ARGS__); }; \
     auto notify = [&]() {                                             \
         std::lock_guard<std::mutex> lk(egmock_mut_##Method);          \
+        EGMOCK_LOG_(#Method " called");                               \
         egmock_called_##Method = true;                                \
         egmock_cond_##Method.notify_all();                            \
     };                                                                \
@@ -105,6 +121,7 @@
  *     EXPECT_TIMEOUT_CALL(account, charge, 100, Currency::USD);
  */
 #define EXPECT_TIMEOUT_CALL(obj, Method, ...) \
+    EGMOCK_LOG_(#Method " expected to call"); \
     (obj).egmock_called_##Method = false;     \
     EXPECT_CALL(obj, egmock_##Method(__VA_ARGS__))
 
@@ -124,6 +141,7 @@
  */
 #define EXPECT_TIMEOUT_CALL_WAIT(obj, Method, timeout)                      \
     {                                                                       \
+        EGMOCK_LOG_("waiting for " #Method " call");                        \
         std::unique_lock<std::mutex> lk((obj).egmock_mut_##Method);         \
         if (!(obj).egmock_called_##Method) {                                \
             auto status = (obj).egmock_cond_##Method.wait_for(lk, timeout); \
@@ -131,4 +149,4 @@
         }                                                                   \
     }
 
-#endif  // ANDROID_HARDWARE_BROADCASTRADIO_V1_1_MOCK_TIMEOUT
+#endif  // ANDROID_HARDWARE_BROADCASTRADIO_VTS_MOCK_TIMEOUT
diff --git a/current.txt b/current.txt
index c18153a..a5ab307 100644
--- a/current.txt
+++ b/current.txt
@@ -255,4 +255,4 @@
 fb92e2b40f8e9d494e8fd3b4ac18499a3216342e7cff160714c3bbf3660b6e79 android.hardware.gnss@1.0::IGnssConfiguration
 251594ea9b27447bfa005ebd806e58fb0ae4aad84a69938129c9800ec0c64eda android.hardware.gnss@1.0::IGnssMeasurementCallback
 4e7169919d24fbe5573e5bcd683d0bd7abf553a4e6c34c41f9dfc1e12050db07 android.hardware.gnss@1.0::IGnssNavigationMessageCallback
-
+b280c4704dfcc548a9bf127b59b7c3578f460c50cce70a06b66fe0df8b27cff0 android.hardware.wifi@1.0::types
diff --git a/keymaster/4.0/default/service.cpp b/keymaster/4.0/default/service.cpp
index f4b5fd3..cfb960a 100644
--- a/keymaster/4.0/default/service.cpp
+++ b/keymaster/4.0/default/service.cpp
@@ -21,8 +21,10 @@
 
 #include <AndroidKeymaster4Device.h>
 
+using android::hardware::keymaster::V4_0::SecurityLevel;
+
 int main() {
-    auto keymaster = ::keymaster::V4_0::ng::CreateKeymasterDevice();
+    auto keymaster = ::keymaster::V4_0::ng::CreateKeymasterDevice(SecurityLevel::SOFTWARE);
     auto status = keymaster->registerAsService();
     if (status != android::OK) {
         LOG(FATAL) << "Could not register service for Keymaster 4.0 (" << status << ")";
diff --git a/keymaster/4.0/support/include/keymasterV4_0/keymaster_tags.h b/keymaster/4.0/support/include/keymasterV4_0/keymaster_tags.h
index 2f9f88b..73e03fb 100644
--- a/keymaster/4.0/support/include/keymasterV4_0/keymaster_tags.h
+++ b/keymaster/4.0/support/include/keymasterV4_0/keymaster_tags.h
@@ -329,6 +329,92 @@
     return accessTagValue(ttag, param);
 }
 
+inline bool operator==(const KeyParameter& a, const KeyParameter& b) {
+    if (a.tag != b.tag) {
+        return false;
+    }
+
+    switch (a.tag) {
+        /* Boolean tags */
+        case Tag::INVALID:
+        case Tag::CALLER_NONCE:
+        case Tag::INCLUDE_UNIQUE_ID:
+        case Tag::BOOTLOADER_ONLY:
+        case Tag::NO_AUTH_REQUIRED:
+        case Tag::ALLOW_WHILE_ON_BODY:
+        case Tag::ROLLBACK_RESISTANCE:
+        case Tag::RESET_SINCE_ID_ROTATION:
+        case Tag::TRUSTED_USER_PRESENCE_REQUIRED:
+            return true;
+
+        /* Integer tags */
+        case Tag::KEY_SIZE:
+        case Tag::MIN_MAC_LENGTH:
+        case Tag::MIN_SECONDS_BETWEEN_OPS:
+        case Tag::MAX_USES_PER_BOOT:
+        case Tag::OS_VERSION:
+        case Tag::OS_PATCHLEVEL:
+        case Tag::MAC_LENGTH:
+        case Tag::AUTH_TIMEOUT:
+            return a.f.integer == b.f.integer;
+
+        /* Long integer tags */
+        case Tag::RSA_PUBLIC_EXPONENT:
+        case Tag::USER_SECURE_ID:
+            return a.f.longInteger == b.f.longInteger;
+
+        /* Date-time tags */
+        case Tag::ACTIVE_DATETIME:
+        case Tag::ORIGINATION_EXPIRE_DATETIME:
+        case Tag::USAGE_EXPIRE_DATETIME:
+        case Tag::CREATION_DATETIME:
+            return a.f.dateTime == b.f.dateTime;
+
+        /* Bytes tags */
+        case Tag::APPLICATION_ID:
+        case Tag::APPLICATION_DATA:
+        case Tag::ROOT_OF_TRUST:
+        case Tag::UNIQUE_ID:
+        case Tag::ATTESTATION_CHALLENGE:
+        case Tag::ATTESTATION_APPLICATION_ID:
+        case Tag::ATTESTATION_ID_BRAND:
+        case Tag::ATTESTATION_ID_DEVICE:
+        case Tag::ATTESTATION_ID_PRODUCT:
+        case Tag::ATTESTATION_ID_SERIAL:
+        case Tag::ATTESTATION_ID_IMEI:
+        case Tag::ATTESTATION_ID_MEID:
+        case Tag::ATTESTATION_ID_MANUFACTURER:
+        case Tag::ATTESTATION_ID_MODEL:
+        case Tag::ASSOCIATED_DATA:
+        case Tag::NONCE:
+            return a.blob == b.blob;
+
+        /* Enum tags */
+        case Tag::PURPOSE:
+            return a.f.purpose == b.f.purpose;
+        case Tag::ALGORITHM:
+            return a.f.algorithm == b.f.algorithm;
+        case Tag::BLOCK_MODE:
+            return a.f.blockMode == b.f.blockMode;
+        case Tag::DIGEST:
+            return a.f.digest == b.f.digest;
+        case Tag::PADDING:
+            return a.f.paddingMode == b.f.paddingMode;
+        case Tag::EC_CURVE:
+            return a.f.ecCurve == b.f.ecCurve;
+        case Tag::BLOB_USAGE_REQUIREMENTS:
+            return a.f.keyBlobUsageRequirements == b.f.keyBlobUsageRequirements;
+        case Tag::USER_AUTH_TYPE:
+            return a.f.integer == b.f.integer;
+        case Tag::ORIGIN:
+            return a.f.origin == b.f.origin;
+        case Tag::HARDWARE_TYPE:
+            return a.f.hardwareType == b.f.hardwareType;
+    }
+
+    return false;
+}
+
 }  // namespace V4_0
 }  // namespace keymaster
 }  // namespace hardware
diff --git a/keymaster/4.0/support/include/keymasterV4_0/openssl_utils.h b/keymaster/4.0/support/include/keymasterV4_0/openssl_utils.h
index 2d3bcf1..cc71dd1 100644
--- a/keymaster/4.0/support/include/keymasterV4_0/openssl_utils.h
+++ b/keymaster/4.0/support/include/keymasterV4_0/openssl_utils.h
@@ -14,6 +14,11 @@
  * limitations under the License.
  */
 
+#ifndef HARDWARE_INTERFACES_KEYMASTER_4_0_SUPPORT_OPENSSL_UTILS_H_
+#define HARDWARE_INTERFACES_KEYMASTER_4_0_SUPPORT_OPENSSL_UTILS_H_
+
+#include <android/hardware/keymaster/4.0/types.h>
+
 template <typename T, void (*F)(T*)>
 struct UniquePtrDeleter {
     void operator()(T* p) const { F(p); }
@@ -51,3 +56,5 @@
     }
     return nullptr;
 }
+
+#endif  // HARDWARE_INTERFACES_KEYMASTER_4_0_SUPPORT_OPENSSL_UTILS_H_
diff --git a/keymaster/4.0/types.hal b/keymaster/4.0/types.hal
index e31804d..e890c6d 100644
--- a/keymaster/4.0/types.hal
+++ b/keymaster/4.0/types.hal
@@ -639,7 +639,7 @@
     SecurityLevel securityLevel;
 
     /**
-     * 32-byte HMAC of the above values, computed as:
+     * 32-byte HMAC-SHA256 of the above values, computed as:
      *
      *    HMAC(H,
      *         "Auth Verification" || challenge || timestamp || securityLevel || parametersVerified)
diff --git a/keymaster/4.0/vts/functional/Android.bp b/keymaster/4.0/vts/functional/Android.bp
index e705d66..d74a16f 100644
--- a/keymaster/4.0/vts/functional/Android.bp
+++ b/keymaster/4.0/vts/functional/Android.bp
@@ -20,6 +20,7 @@
     srcs: [
         "HmacKeySharingTest.cpp",
         "KeymasterHidlTest.cpp",
+        "VerificationTokenTest.cpp",
         "keymaster_hidl_hal_test.cpp",
     ],
     static_libs: [
diff --git a/keymaster/4.0/vts/functional/KeymasterHidlTest.h b/keymaster/4.0/vts/functional/KeymasterHidlTest.h
index 0c73f05..6d28f17 100644
--- a/keymaster/4.0/vts/functional/KeymasterHidlTest.h
+++ b/keymaster/4.0/vts/functional/KeymasterHidlTest.h
@@ -205,6 +205,7 @@
     std::pair<ErrorCode, HidlBuf> UpgradeKey(const HidlBuf& key_blob);
 
     static bool IsSecure() { return securityLevel_ != SecurityLevel::SOFTWARE; }
+    static SecurityLevel SecLevel() { return securityLevel_; }
 
     HidlBuf key_blob_;
     KeyCharacteristics key_characteristics_;
diff --git a/keymaster/4.0/vts/functional/VerificationTokenTest.cpp b/keymaster/4.0/vts/functional/VerificationTokenTest.cpp
new file mode 100644
index 0000000..6afba0c
--- /dev/null
+++ b/keymaster/4.0/vts/functional/VerificationTokenTest.cpp
@@ -0,0 +1,132 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "KeymasterHidlTest.h"
+
+namespace android {
+namespace hardware {
+namespace keymaster {
+namespace V4_0 {
+namespace test {
+
+class VerificationTokenTest : public KeymasterHidlTest {
+   protected:
+    struct VerifyAuthorizationResult {
+        bool callSuccessful;
+        ErrorCode error;
+        VerificationToken token;
+    };
+
+    VerifyAuthorizationResult verifyAuthorization(uint64_t operationHandle,
+                                                  const AuthorizationSet& paramsToVerify,
+                                                  const HardwareAuthToken& authToken) {
+        VerifyAuthorizationResult result;
+        result.callSuccessful =
+            keymaster()
+                .verifyAuthorization(operationHandle, paramsToVerify.hidl_data(), authToken,
+                                     [&](auto error, auto token) {
+                                         result.error = error;
+                                         result.token = token;
+                                     })
+                .isOk();
+        return result;
+    }
+
+    uint64_t getTime() {
+        struct timespec timespec;
+        EXPECT_EQ(0, clock_gettime(CLOCK_BOOTTIME, &timespec));
+        return timespec.tv_sec * 1000 + timespec.tv_nsec / 1000000;
+    }
+
+    int sleep_ms(uint32_t milliseconds) {
+        struct timespec sleep_time = {static_cast<time_t>(milliseconds / 1000),
+                                      static_cast<long>(milliseconds % 1000) * 1000000};
+        while (sleep_time.tv_sec || sleep_time.tv_nsec) {
+            if (nanosleep(&sleep_time /* to wait */,
+                          &sleep_time /* remaining (on interrruption) */) == 0) {
+                sleep_time = {};
+            } else {
+                if (errno != EINTR) return errno;
+            }
+        }
+        return 0;
+    }
+
+};  // namespace test
+
+/*
+ * VerificationTokens exist to facilitate cross-Keymaster verification of requirements.  As
+ * such, the precise capabilities required will vary depending on the specific vendor
+ * implementations. Essentially, VerificationTokens are a "hook" to enable vendor
+ * implementations to communicate, so the precise usage is defined by those vendors.  The only
+ * thing we really can test is that tokens can be created by TEE keymasters, and that the
+ * timestamps increase as expected.
+ */
+TEST_F(VerificationTokenTest, TestCreation) {
+    auto result1 = verifyAuthorization(
+        1 /* operation handle */, AuthorizationSet() /* paramtersToVerify */, HardwareAuthToken());
+    ASSERT_TRUE(result1.callSuccessful);
+    auto result1_time = getTime();
+
+    if (SecLevel() == SecurityLevel::STRONGBOX) {
+        // StrongBox should not implement verifyAuthorization.
+        EXPECT_EQ(ErrorCode::UNIMPLEMENTED, result1.error);
+        return;
+    }
+
+    EXPECT_EQ(ErrorCode::OK, result1.error);
+    EXPECT_EQ(1U, result1.token.challenge);
+    EXPECT_EQ(SecLevel(), result1.token.securityLevel);
+    EXPECT_EQ(0U, result1.token.parametersVerified.size())
+        << "We didn't supply any parameters to verify";
+    EXPECT_GT(result1.token.timestamp, 0U);
+
+    constexpr uint32_t time_to_sleep = 200;
+    sleep_ms(time_to_sleep);
+
+    auto result2 = verifyAuthorization(
+        2 /* operation handle */, AuthorizationSet() /* paramtersToVerify */, HardwareAuthToken());
+    ASSERT_TRUE(result2.callSuccessful);
+    auto result2_time = getTime();
+    EXPECT_EQ(ErrorCode::OK, result2.error);
+    EXPECT_EQ(2U, result2.token.challenge);
+    EXPECT_EQ(SecLevel(), result2.token.securityLevel);
+    EXPECT_EQ(0U, result2.token.parametersVerified.size())
+        << "We didn't supply any parameters to verify";
+
+    auto host_time_delta = result2_time - result1_time;
+
+    EXPECT_GE(host_time_delta, time_to_sleep)
+        << "We slept for " << time_to_sleep << " ms, the clock must have advanced by that much";
+    EXPECT_LE(host_time_delta, time_to_sleep + 10)
+        << "The verifyAuthorization call took more than 10 ms?  That's awful!";
+
+    auto km_time_delta = result2.token.timestamp - result1.token.timestamp;
+
+    // If not too much else is going on on the system, the time delta should be quite close.  Allow
+    // 2 ms of slop just to avoid test flakiness.
+    //
+    // TODO(swillden): see if we can output values so they can be gathered across many runs and
+    // report if times aren't nearly always <1ms apart.
+    EXPECT_LE(host_time_delta, km_time_delta + 2);
+    EXPECT_LE(km_time_delta, host_time_delta + 2);
+}
+
+}  // namespace test
+}  // namespace V4_0
+}  // namespace keymaster
+}  // namespace hardware
+}  // namespace android
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 cb6ade2..31d6ad1 100644
--- a/keymaster/4.0/vts/functional/keymaster_hidl_hal_test.cpp
+++ b/keymaster/4.0/vts/functional/keymaster_hidl_hal_test.cpp
@@ -52,92 +52,6 @@
 namespace keymaster {
 namespace V4_0 {
 
-bool operator==(const KeyParameter& a, const KeyParameter& b) {
-    if (a.tag != b.tag) {
-        return false;
-    }
-
-    switch (a.tag) {
-        /* Boolean tags */
-        case Tag::INVALID:
-        case Tag::CALLER_NONCE:
-        case Tag::INCLUDE_UNIQUE_ID:
-        case Tag::BOOTLOADER_ONLY:
-        case Tag::NO_AUTH_REQUIRED:
-        case Tag::ALLOW_WHILE_ON_BODY:
-        case Tag::ROLLBACK_RESISTANCE:
-        case Tag::RESET_SINCE_ID_ROTATION:
-        case Tag::TRUSTED_USER_PRESENCE_REQUIRED:
-            return true;
-
-        /* Integer tags */
-        case Tag::KEY_SIZE:
-        case Tag::MIN_MAC_LENGTH:
-        case Tag::MIN_SECONDS_BETWEEN_OPS:
-        case Tag::MAX_USES_PER_BOOT:
-        case Tag::OS_VERSION:
-        case Tag::OS_PATCHLEVEL:
-        case Tag::MAC_LENGTH:
-        case Tag::AUTH_TIMEOUT:
-            return a.f.integer == b.f.integer;
-
-        /* Long integer tags */
-        case Tag::RSA_PUBLIC_EXPONENT:
-        case Tag::USER_SECURE_ID:
-            return a.f.longInteger == b.f.longInteger;
-
-        /* Date-time tags */
-        case Tag::ACTIVE_DATETIME:
-        case Tag::ORIGINATION_EXPIRE_DATETIME:
-        case Tag::USAGE_EXPIRE_DATETIME:
-        case Tag::CREATION_DATETIME:
-            return a.f.dateTime == b.f.dateTime;
-
-        /* Bytes tags */
-        case Tag::APPLICATION_ID:
-        case Tag::APPLICATION_DATA:
-        case Tag::ROOT_OF_TRUST:
-        case Tag::UNIQUE_ID:
-        case Tag::ATTESTATION_CHALLENGE:
-        case Tag::ATTESTATION_APPLICATION_ID:
-        case Tag::ATTESTATION_ID_BRAND:
-        case Tag::ATTESTATION_ID_DEVICE:
-        case Tag::ATTESTATION_ID_PRODUCT:
-        case Tag::ATTESTATION_ID_SERIAL:
-        case Tag::ATTESTATION_ID_IMEI:
-        case Tag::ATTESTATION_ID_MEID:
-        case Tag::ATTESTATION_ID_MANUFACTURER:
-        case Tag::ATTESTATION_ID_MODEL:
-        case Tag::ASSOCIATED_DATA:
-        case Tag::NONCE:
-            return a.blob == b.blob;
-
-        /* Enum tags */
-        case Tag::PURPOSE:
-            return a.f.purpose == b.f.purpose;
-        case Tag::ALGORITHM:
-            return a.f.algorithm == b.f.algorithm;
-        case Tag::BLOCK_MODE:
-            return a.f.blockMode == b.f.blockMode;
-        case Tag::DIGEST:
-            return a.f.digest == b.f.digest;
-        case Tag::PADDING:
-            return a.f.paddingMode == b.f.paddingMode;
-        case Tag::EC_CURVE:
-            return a.f.ecCurve == b.f.ecCurve;
-        case Tag::BLOB_USAGE_REQUIREMENTS:
-            return a.f.keyBlobUsageRequirements == b.f.keyBlobUsageRequirements;
-        case Tag::USER_AUTH_TYPE:
-            return a.f.integer == b.f.integer;
-        case Tag::ORIGIN:
-            return a.f.origin == b.f.origin;
-        case Tag::HARDWARE_TYPE:
-            return a.f.hardwareType == b.f.hardwareType;
-    }
-
-    return false;
-}
-
 bool operator==(const AuthorizationSet& a, const AuthorizationSet& b) {
     return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin());
 }
diff --git a/wifi/1.0/types.hal b/wifi/1.0/types.hal
index b9fb0bd..4b8d68a 100644
--- a/wifi/1.0/types.hal
+++ b/wifi/1.0/types.hal
@@ -1411,7 +1411,8 @@
   vec<uint8_t> extendedServiceSpecificInfo;
   /**
    * The match filter from the discovery packet (publish or subscribe) which caused service
-   * discovery. Matches the peer's |NanDiscoveryCommonConfig.txMatchFilter|.
+   * discovery. Matches the |NanDiscoveryCommonConfig.txMatchFilter| of the peer's Unsolicited
+   * publish message or of the local device's Active subscribe message.
    * Max length: |NanCapabilities.maxMatchFilterLen|.
    * NAN Spec: Service Descriptor Attribute (SDA) / Matching Filter
    */
diff --git a/wifi/1.2/default/hidl_struct_util.cpp b/wifi/1.2/default/hidl_struct_util.cpp
index 3ca35f7..f87828c 100644
--- a/wifi/1.2/default/hidl_struct_util.cpp
+++ b/wifi/1.2/default/hidl_struct_util.cpp
@@ -1141,6 +1141,8 @@
     legacy_request->config_dw_early_termination = 1;
     legacy_request->enable_dw_termination =
         hidl_request2.enableDiscoveryWindowEarlyTermination;
+    legacy_request->config_enable_ranging = 1;
+    legacy_request->enable_ranging = hidl_request2.enableRanging;
 
     return true;
 }
@@ -1650,6 +1652,8 @@
     legacy_request->config_dw_early_termination = 1;
     legacy_request->enable_dw_termination =
         hidl_request2.enableDiscoveryWindowEarlyTermination;
+    legacy_request->config_enable_ranging = 1;
+    legacy_request->enable_ranging = hidl_request2.enableRanging;
 
     return true;
 }
diff --git a/wifi/1.2/types.hal b/wifi/1.2/types.hal
index 60f4b1f..1636ae8 100644
--- a/wifi/1.2/types.hal
+++ b/wifi/1.2/types.hal
@@ -49,6 +49,11 @@
      * lower power consumption, but may result in some missed messages and hence increased latency.
      */
     bool enableDiscoveryWindowEarlyTermination;
+    /**
+     * Controls whether NAN RTT (ranging) is permitted. Global flag on any NAN RTT operations are
+     * allowed. Controls ranging in the context of discovery as well as direct RTT.
+     */
+    bool enableRanging;
 };
 
 /**