Merge changes I843fd9ef,Ife0a5721 into qt-dev

* changes:
  Prevent entries with identical times
  Refactor VelocityTracker_test
diff --git a/cmds/installd/dexopt.cpp b/cmds/installd/dexopt.cpp
index a5cc0df..dbb4f22 100644
--- a/cmds/installd/dexopt.cpp
+++ b/cmds/installd/dexopt.cpp
@@ -534,7 +534,7 @@
         }
         AddRuntimeArg(target_sdk_version_arg);
         if (enable_hidden_api_checks) {
-            AddRuntimeArg("-Xhidden-api-checks");
+            AddRuntimeArg("-Xhidden-api-policy:enabled");
         }
 
         if (dex_metadata_fd > -1) {
diff --git a/libs/binder/aidl/android/content/pm/IPackageManagerNative.aidl b/libs/binder/aidl/android/content/pm/IPackageManagerNative.aidl
index b1c577e..70ed80d 100644
--- a/libs/binder/aidl/android/content/pm/IPackageManagerNative.aidl
+++ b/libs/binder/aidl/android/content/pm/IPackageManagerNative.aidl
@@ -66,15 +66,12 @@
     const int LOCATION_VENDOR = 0x2;
     /*  ApplicationInfo.isProduct() == true */
     const int LOCATION_PRODUCT = 0x4;
-    /*  ApplicationInfo.isProductServices() == true */
-    const int LOCATION_PRODUCT_SERVICES = 0x8;
 
     /**
      * Returns a set of bitflags about package location.
      * LOCATION_SYSTEM: getApplicationInfo(packageName).isSystemApp()
      * LOCATION_VENDOR: getApplicationInfo(packageName).isVendor()
      * LOCATION_PRODUCT: getApplicationInfo(packageName).isProduct()
-     * LOCATION_PRODUCT_SERVICES: getApplicationInfo(packageName).isProductService()
      */
     int getLocationFlags(in @utf8InCpp String packageName);
 }
diff --git a/libs/dumputils/dump_utils.cpp b/libs/dumputils/dump_utils.cpp
index 04884bb..180fd97 100644
--- a/libs/dumputils/dump_utils.cpp
+++ b/libs/dumputils/dump_utils.cpp
@@ -31,6 +31,7 @@
         "/system/bin/mediaextractor", // media.extractor
         "/system/bin/mediametrics", // media.metrics
         "/system/bin/mediaserver",
+        "/system/bin/netd",
         "/system/bin/sdcard",
         "/system/bin/statsd",
         "/system/bin/surfaceflinger",
@@ -51,6 +52,7 @@
         "android.hardware.health@2.0::IHealth",
         "android.hardware.media.omx@1.0::IOmx",
         "android.hardware.media.omx@1.0::IOmxStore",
+        "android.hardware.power.stats@1.0::IPowerStats",
         "android.hardware.sensors@1.0::ISensors",
         "android.hardware.vr@1.0::IVr",
         NULL,
diff --git a/libs/gui/BufferQueueCore.cpp b/libs/gui/BufferQueueCore.cpp
index 96c55ac..e0e3431 100644
--- a/libs/gui/BufferQueueCore.cpp
+++ b/libs/gui/BufferQueueCore.cpp
@@ -73,6 +73,8 @@
     mActiveBuffers(),
     mDequeueCondition(),
     mDequeueBufferCannotBlock(false),
+    mQueueBufferCanDrop(false),
+    mLegacyBufferDrop(true),
     mDefaultBufferFormat(PIXEL_FORMAT_RGBA_8888),
     mDefaultWidth(1),
     mDefaultHeight(1),
@@ -117,6 +119,8 @@
                             mMaxAcquiredBufferCount, mMaxDequeuedBufferCount);
     outResult->appendFormat("%s  mDequeueBufferCannotBlock=%d mAsyncMode=%d\n", prefix.string(),
                             mDequeueBufferCannotBlock, mAsyncMode);
+    outResult->appendFormat("%s  mQueueBufferCanDrop=%d mLegacyBufferDrop=%d\n", prefix.string(),
+                            mQueueBufferCanDrop, mLegacyBufferDrop);
     outResult->appendFormat("%s  default-size=[%dx%d] default-format=%d ", prefix.string(),
                             mDefaultWidth, mDefaultHeight, mDefaultBufferFormat);
     outResult->appendFormat("transform-hint=%02x frame-counter=%" PRIu64, mTransformHint,
diff --git a/libs/gui/BufferQueueProducer.cpp b/libs/gui/BufferQueueProducer.cpp
index 72ae375..4ff69c5 100644
--- a/libs/gui/BufferQueueProducer.cpp
+++ b/libs/gui/BufferQueueProducer.cpp
@@ -889,7 +889,8 @@
         item.mFence = acquireFence;
         item.mFenceTime = acquireFenceTime;
         item.mIsDroppable = mCore->mAsyncMode ||
-                mCore->mDequeueBufferCannotBlock ||
+                (!mCore->mLegacyBufferDrop && mConsumerIsSurfaceFlinger) ||
+                (mCore->mLegacyBufferDrop && mCore->mQueueBufferCanDrop) ||
                 (mCore->mSharedBufferMode && mCore->mSharedBufferSlot == slot);
         item.mSurfaceDamage = surfaceDamage;
         item.mQueuedBuffer = true;
@@ -1230,9 +1231,11 @@
     mCore->mConnectedPid = BufferQueueThreadState::getCallingPid();
     mCore->mBufferHasBeenQueued = false;
     mCore->mDequeueBufferCannotBlock = false;
-    if (mDequeueTimeout < 0) {
-        mCore->mDequeueBufferCannotBlock =
-                mCore->mConsumerControlledByApp && producerControlledByApp;
+    mCore->mQueueBufferCanDrop = false;
+    mCore->mLegacyBufferDrop = true;
+    if (mCore->mConsumerControlledByApp && producerControlledByApp) {
+        mCore->mDequeueBufferCannotBlock = mDequeueTimeout < 0;
+        mCore->mQueueBufferCanDrop = mDequeueTimeout <= 0;
     }
 
     mCore->mAllowAllocation = true;
@@ -1516,12 +1519,26 @@
     }
 
     mDequeueTimeout = timeout;
-    mCore->mDequeueBufferCannotBlock = false;
+    if (timeout >= 0) {
+        mCore->mDequeueBufferCannotBlock = false;
+        if (timeout != 0) {
+            mCore->mQueueBufferCanDrop = false;
+        }
+    }
 
     VALIDATE_CONSISTENCY();
     return NO_ERROR;
 }
 
+status_t BufferQueueProducer::setLegacyBufferDrop(bool drop) {
+    ATRACE_CALL();
+    BQ_LOGV("setLegacyBufferDrop: drop = %d", drop);
+
+    std::lock_guard<std::mutex> lock(mCore->mMutex);
+    mCore->mLegacyBufferDrop = drop;
+    return NO_ERROR;
+}
+
 status_t BufferQueueProducer::getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer,
         sp<Fence>* outFence, float outTransformMatrix[16]) {
     ATRACE_CALL();
diff --git a/libs/gui/IGraphicBufferProducer.cpp b/libs/gui/IGraphicBufferProducer.cpp
index bf44121..0e03b7d 100644
--- a/libs/gui/IGraphicBufferProducer.cpp
+++ b/libs/gui/IGraphicBufferProducer.cpp
@@ -72,6 +72,7 @@
     GET_FRAME_TIMESTAMPS,
     GET_UNIQUE_ID,
     GET_CONSUMER_USAGE,
+    SET_LEGACY_BUFFER_DROP,
 };
 
 class BpGraphicBufferProducer : public BpInterface<IGraphicBufferProducer>
@@ -437,6 +438,20 @@
         return reply.readInt32();
     }
 
+    virtual status_t setLegacyBufferDrop(bool drop) {
+        Parcel data, reply;
+        data.writeInterfaceToken(
+                IGraphicBufferProducer::getInterfaceDescriptor());
+        data.writeInt32(drop);
+        status_t result = remote()->transact(SET_LEGACY_BUFFER_DROP,
+                data, &reply);
+        if (result != NO_ERROR) {
+            return result;
+        }
+        result = reply.readInt32();
+        return result;
+    }
+
     virtual status_t getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer,
             sp<Fence>* outFence, float outTransformMatrix[16]) override {
         Parcel data, reply;
@@ -637,6 +652,10 @@
         return mBase->setDequeueTimeout(timeout);
     }
 
+    status_t setLegacyBufferDrop(bool drop) override {
+        return mBase->setLegacyBufferDrop(drop);
+    }
+
     status_t getLastQueuedBuffer(
             sp<GraphicBuffer>* outBuffer,
             sp<Fence>* outFence,
@@ -663,6 +682,12 @@
 
 // ----------------------------------------------------------------------
 
+status_t IGraphicBufferProducer::setLegacyBufferDrop(bool drop) {
+    // No-op for IGBP other than BufferQueue.
+    (void) drop;
+    return INVALID_OPERATION;
+}
+
 status_t IGraphicBufferProducer::exportToParcel(Parcel* parcel) {
     status_t res = OK;
     res = parcel->writeUint32(USE_BUFFER_QUEUE);
@@ -1018,6 +1043,13 @@
             }
             return NO_ERROR;
         }
+        case SET_LEGACY_BUFFER_DROP: {
+            CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
+            bool drop = data.readInt32();
+            int result = setLegacyBufferDrop(drop);
+            reply->writeInt32(result);
+            return NO_ERROR;
+        }
     }
     return BBinder::onTransact(code, data, reply, flags);
 }
diff --git a/libs/gui/Surface.cpp b/libs/gui/Surface.cpp
index 93b4191..e6eb327 100644
--- a/libs/gui/Surface.cpp
+++ b/libs/gui/Surface.cpp
@@ -829,8 +829,9 @@
     mDefaultHeight = output.height;
     mNextFrameNumber = output.nextFrameNumber;
 
-    // Disable transform hint if sticky transform is set.
-    if (mStickyTransform == 0) {
+    // Ignore transform hint if sticky transform is set or transform to display inverse flag is
+    // set.
+    if (mStickyTransform == 0 && !transformToDisplayInverse()) {
         mTransformHint = output.transformHint;
     }
 
@@ -1271,6 +1272,11 @@
     return getConsumerUsage(usage);
 }
 
+bool Surface::transformToDisplayInverse() {
+    return (mTransform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) ==
+            NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
+}
+
 int Surface::connect(int api) {
     static sp<IProducerListener> listener = new DummyProducerListener();
     return connect(api, listener);
@@ -1293,8 +1299,10 @@
         mDefaultHeight = output.height;
         mNextFrameNumber = output.nextFrameNumber;
 
-        // Disable transform hint if sticky transform is set.
-        if (mStickyTransform == 0) {
+        // Ignore transform hint if sticky transform is set or transform to display inverse flag is
+        // set. Transform hint should be ignored if the client is expected to always submit buffers
+        // in the same orientation.
+        if (mStickyTransform == 0 && !transformToDisplayInverse()) {
             mTransformHint = output.transformHint;
         }
 
@@ -1591,6 +1599,13 @@
     ATRACE_CALL();
     ALOGV("Surface::setBuffersTransform");
     Mutex::Autolock lock(mMutex);
+    // Ensure NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY is sticky. If the client sets the flag, do not
+    // override it until the surface is disconnected. This is a temporary workaround for camera
+    // until they switch to using Buffer State Layers. Currently if client sets the buffer transform
+    // it may be overriden by the buffer producer when the producer sets the buffer transform.
+    if (transformToDisplayInverse()) {
+        transform |= NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
+    }
     mTransform = transform;
     return NO_ERROR;
 }
diff --git a/libs/gui/include/gui/BufferQueueCore.h b/libs/gui/include/gui/BufferQueueCore.h
index 0e80283..9c0ee99 100644
--- a/libs/gui/include/gui/BufferQueueCore.h
+++ b/libs/gui/include/gui/BufferQueueCore.h
@@ -226,6 +226,16 @@
     // consumer are controlled by the application.
     bool mDequeueBufferCannotBlock;
 
+    // mQueueBufferCanDrop indicates whether queueBuffer is allowed to drop
+    // buffers in non-async mode. This flag is set during connect when both the
+    // producer and consumer are controlled by application.
+    bool mQueueBufferCanDrop;
+
+    // mLegacyBufferDrop indicates whether mQueueBufferCanDrop is in effect.
+    // If this flag is set mQueueBufferCanDrop is working as explained. If not
+    // queueBuffer will not drop buffers unless consumer is SurfaceFlinger.
+    bool mLegacyBufferDrop;
+
     // mDefaultBufferFormat can be set so it will override the buffer format
     // when it isn't specified in dequeueBuffer.
     PixelFormat mDefaultBufferFormat;
diff --git a/libs/gui/include/gui/BufferQueueProducer.h b/libs/gui/include/gui/BufferQueueProducer.h
index 415e2a6..d2a47a6 100644
--- a/libs/gui/include/gui/BufferQueueProducer.h
+++ b/libs/gui/include/gui/BufferQueueProducer.h
@@ -174,6 +174,9 @@
     // See IGraphicBufferProducer::setDequeueTimeout
     virtual status_t setDequeueTimeout(nsecs_t timeout) override;
 
+    // see IGraphicBufferProducer::setLegacyBufferDrop
+    virtual status_t setLegacyBufferDrop(bool drop);
+
     // See IGraphicBufferProducer::getLastQueuedBuffer
     virtual status_t getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer,
             sp<Fence>* outFence, float outTransformMatrix[16]) override;
diff --git a/libs/gui/include/gui/IGraphicBufferProducer.h b/libs/gui/include/gui/IGraphicBufferProducer.h
index 9f7e22b..3dde8c8 100644
--- a/libs/gui/include/gui/IGraphicBufferProducer.h
+++ b/libs/gui/include/gui/IGraphicBufferProducer.h
@@ -592,12 +592,20 @@
     // non-blocking mode and its corresponding spare buffer (which is used to
     // ensure a buffer is always available).
     //
+    // Note well: queueBuffer will stop buffer dropping behavior if timeout is
+    // strictly positive. If timeout is zero or negative, previous buffer
+    // dropping behavior will not be changed.
+    //
     // Return of a value other than NO_ERROR means an error has occurred:
     // * BAD_VALUE - Failure to adjust the number of available slots. This can
     //               happen because of trying to allocate/deallocate the async
     //               buffer.
     virtual status_t setDequeueTimeout(nsecs_t timeout) = 0;
 
+    // Used to enable/disable buffer drop behavior of queueBuffer.
+    // If it's not used, legacy drop behavior will be retained.
+    virtual status_t setLegacyBufferDrop(bool drop);
+
     // Returns the last queued buffer along with a fence which must signal
     // before the contents of the buffer are read. If there are no buffers in
     // the queue, outBuffer will be populated with nullptr and outFence will be
diff --git a/libs/gui/include/gui/Surface.h b/libs/gui/include/gui/Surface.h
index 248e105..0c471bb 100644
--- a/libs/gui/include/gui/Surface.h
+++ b/libs/gui/include/gui/Surface.h
@@ -230,6 +230,7 @@
     int dispatchGetWideColorSupport(va_list args);
     int dispatchGetHdrSupport(va_list args);
     int dispatchGetConsumerUsage64(va_list args);
+    bool transformToDisplayInverse();
 
 protected:
     virtual int dequeueBuffer(ANativeWindowBuffer** buffer, int* fenceFd);
diff --git a/libs/gui/include/gui/SurfaceControl.h b/libs/gui/include/gui/SurfaceControl.h
index 23bfc02..55efcbf 100644
--- a/libs/gui/include/gui/SurfaceControl.h
+++ b/libs/gui/include/gui/SurfaceControl.h
@@ -84,9 +84,6 @@
     
     explicit SurfaceControl(const sp<SurfaceControl>& other);
 
-    SurfaceControl(const sp<SurfaceComposerClient>& client, const sp<IBinder>& handle,
-                   const sp<IGraphicBufferProducer>& gbp, bool owned);
-
 private:
     // can't be copied
     SurfaceControl& operator = (SurfaceControl& rhs);
@@ -95,6 +92,12 @@
     friend class SurfaceComposerClient;
     friend class Surface;
 
+    SurfaceControl(
+            const sp<SurfaceComposerClient>& client,
+            const sp<IBinder>& handle,
+            const sp<IGraphicBufferProducer>& gbp,
+            bool owned);
+
     ~SurfaceControl();
 
     sp<Surface> generateSurfaceLocked() const;
diff --git a/libs/ui/Gralloc3.cpp b/libs/ui/Gralloc3.cpp
index 7f8e57c..eb43765 100644
--- a/libs/ui/Gralloc3.cpp
+++ b/libs/ui/Gralloc3.cpp
@@ -28,7 +28,7 @@
 #pragma clang diagnostic pop
 
 using android::hardware::graphics::allocator::V3_0::IAllocator;
-using android::hardware::graphics::common::V1_1::BufferUsage;
+using android::hardware::graphics::common::V1_2::BufferUsage;
 using android::hardware::graphics::mapper::V3_0::BufferDescriptor;
 using android::hardware::graphics::mapper::V3_0::Error;
 using android::hardware::graphics::mapper::V3_0::IMapper;
@@ -44,11 +44,7 @@
     static const uint64_t validUsageBits = []() -> uint64_t {
         uint64_t bits = 0;
         for (const auto bit :
-             hardware::hidl_enum_range<hardware::graphics::common::V1_0::BufferUsage>()) {
-            bits = bits | bit;
-        }
-        for (const auto bit :
-             hardware::hidl_enum_range<hardware::graphics::common::V1_1::BufferUsage>()) {
+             hardware::hidl_enum_range<hardware::graphics::common::V1_2::BufferUsage>()) {
             bits = bits | bit;
         }
         return bits;
@@ -71,7 +67,7 @@
     outDescriptorInfo->width = width;
     outDescriptorInfo->height = height;
     outDescriptorInfo->layerCount = layerCount;
-    outDescriptorInfo->format = static_cast<hardware::graphics::common::V1_1::PixelFormat>(format);
+    outDescriptorInfo->format = static_cast<hardware::graphics::common::V1_2::PixelFormat>(format);
     outDescriptorInfo->usage = usage;
 }
 
diff --git a/opengl/libs/EGL/egl_display.cpp b/opengl/libs/EGL/egl_display.cpp
index 12947b2..eb970d9 100644
--- a/opengl/libs/EGL/egl_display.cpp
+++ b/opengl/libs/EGL/egl_display.cpp
@@ -336,56 +336,10 @@
         mVendorString = sVendorString;
         mVersionString.clear();
         cnx->driverVersion = EGL_MAKE_VERSION(1, 4, 0);
+        mVersionString = sVersionString14;
         if ((cnx->major == 1) && (cnx->minor == 5)) {
             mVersionString = sVersionString15;
             cnx->driverVersion = EGL_MAKE_VERSION(1, 5, 0);
-        } else if ((cnx->major == 1) && (cnx->minor == 4)) {
-            /* Querying extension strings for type Client */
-            std::string typesExtString;
-            static const char* clientExtensions =
-                    cnx->egl.eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
-            if (clientExtensions != nullptr && strlen(clientExtensions) > 0) {
-                typesExtString.append(clientExtensions);
-                typesExtString.append(" ");
-            }
-
-            /* Adding extension strings for type Display */
-            typesExtString.append(disp.queryString.extensions);
-            mVersionString = sVersionString14;
-            // Extensions needed for an EGL 1.4 implementation to be
-            // able to support EGL 1.5 functionality
-            std::vector<const char*> egl15extensions = {
-                    "EGL_EXT_client_extensions",
-                    // "EGL_EXT_platform_base",  // implemented by EGL runtime
-                    "EGL_KHR_image_base",
-                    "EGL_KHR_fence_sync",
-                    "EGL_KHR_wait_sync",
-                    "EGL_KHR_create_context",
-                    "EGL_EXT_create_context_robustness",
-                    "EGL_KHR_gl_colorspace",
-                    "EGL_ANDROID_native_fence_sync",
-            };
-            bool extensionsFound = true;
-            for (const auto& name : egl15extensions) {
-                extensionsFound &= findExtension(typesExtString.c_str(), name);
-                ALOGV("Extension %s: %s", name,
-                      findExtension(typesExtString.c_str(), name) ? "Found" : "Missing");
-            }
-            // NOTE: From the spec:
-            // Creation of fence sync objects requires support from the bound
-            // client API, and will not succeed unless the client API satisfies:
-            // client API is OpenGL ES, and either the OpenGL ES version is 3.0
-            // or greater, or the GL_OES_EGL_sync extension is supported.
-            // We don't have a way to check the GL_EXTENSIONS string at this
-            // point in the code, assume that GL_OES_EGL_sync is supported
-            // because EGL_KHR_fence_sync is supported (as verified above).
-            if (extensionsFound) {
-                // Have everything needed to emulate EGL 1.5 so report EGL 1.5
-                // to the application.
-                mVersionString = sVersionString15;
-                cnx->major = 1;
-                cnx->minor = 5;
-            }
         }
         if (mVersionString.empty()) {
             ALOGW("Unexpected driver version: %d.%d, want 1.4 or 1.5", cnx->major, cnx->minor);
diff --git a/opengl/tools/glgen/stubs/egl/EGL15cHeader.cpp b/opengl/tools/glgen/stubs/egl/EGL15cHeader.cpp
index 8bb0c6a..34cb3e1 100644
--- a/opengl/tools/glgen/stubs/egl/EGL15cHeader.cpp
+++ b/opengl/tools/glgen/stubs/egl/EGL15cHeader.cpp
@@ -35,16 +35,6 @@
 static jclass eglsurfaceClass;
 static jclass eglconfigClass;
 static jclass eglcontextClass;
-static jclass bufferClass;
-static jclass nioAccessClass;
-
-static jfieldID positionID;
-static jfieldID limitID;
-static jfieldID elementSizeShiftID;
-
-static jmethodID getBasePointerID;
-static jmethodID getBaseArrayID;
-static jmethodID getBaseArrayOffsetID;
 
 static jmethodID egldisplayGetHandleID;
 static jmethodID eglconfigGetHandleID;
@@ -116,24 +106,6 @@
     _env->SetStaticObjectField(eglClass, noSurfaceFieldID, eglNoSurfaceObject);
 
     // EGL 1.5 init
-    jclass nioAccessClassLocal = _env->FindClass("java/nio/NIOAccess");
-    nioAccessClass = (jclass) _env->NewGlobalRef(nioAccessClassLocal);
-
-    jclass bufferClassLocal = _env->FindClass("java/nio/Buffer");
-    bufferClass = (jclass) _env->NewGlobalRef(bufferClassLocal);
-
-    getBasePointerID = _env->GetStaticMethodID(nioAccessClass,
-            "getBasePointer", "(Ljava/nio/Buffer;)J");
-    getBaseArrayID = _env->GetStaticMethodID(nioAccessClass,
-            "getBaseArray", "(Ljava/nio/Buffer;)Ljava/lang/Object;");
-    getBaseArrayOffsetID = _env->GetStaticMethodID(nioAccessClass,
-            "getBaseArrayOffset", "(Ljava/nio/Buffer;)I");
-
-    positionID = _env->GetFieldID(bufferClass, "position", "I");
-    limitID = _env->GetFieldID(bufferClass, "limit", "I");
-    elementSizeShiftID =
-        _env->GetFieldID(bufferClass, "_elementSizeShift", "I");
-
     jclass eglimageClassLocal = _env->FindClass("android/opengl/EGLImage");
     eglimageClass = (jclass) _env->NewGlobalRef(eglimageClassLocal);
     jclass eglsyncClassLocal = _env->FindClass("android/opengl/EGLSync");
@@ -160,23 +132,17 @@
     jint elementSizeShift;
     jlong pointer;
 
-    position = _env->GetIntField(buffer, positionID);
-    limit = _env->GetIntField(buffer, limitID);
-    elementSizeShift = _env->GetIntField(buffer, elementSizeShiftID);
+    pointer = jniGetNioBufferFields(_env, buffer, &position, &limit, &elementSizeShift);
     *remaining = (limit - position) << elementSizeShift;
-    pointer = _env->CallStaticLongMethod(nioAccessClass,
-            getBasePointerID, buffer);
     if (pointer != 0L) {
-        *array = NULL;
+        *array = nullptr;
+        pointer += position << elementSizeShift;
         return reinterpret_cast<void*>(pointer);
     }
 
-    *array = (jarray) _env->CallStaticObjectMethod(nioAccessClass,
-            getBaseArrayID, buffer);
-    *offset = _env->CallStaticIntMethod(nioAccessClass,
-            getBaseArrayOffsetID, buffer);
-
-    return NULL;
+    *array = jniGetNioBufferBaseArray(_env, buffer);
+    *offset = jniGetNioBufferBaseArrayOffset(_env, buffer);
+    return nullptr;
 }
 
 static void
diff --git a/opengl/tools/glgen/stubs/gles11/common.cpp b/opengl/tools/glgen/stubs/gles11/common.cpp
index 51e62ed..e763b4e 100644
--- a/opengl/tools/glgen/stubs/gles11/common.cpp
+++ b/opengl/tools/glgen/stubs/gles11/common.cpp
@@ -4,15 +4,6 @@
 #include <utils/misc.h>
 #include <assert.h>
 
-static jclass nioAccessClass;
-static jclass bufferClass;
-static jmethodID getBasePointerID;
-static jmethodID getBaseArrayID;
-static jmethodID getBaseArrayOffsetID;
-static jfieldID positionID;
-static jfieldID limitID;
-static jfieldID elementSizeShiftID;
-
 
 /* special calls implemented in Android's GLES wrapper used to more
  * efficiently bound-check passed arrays */
@@ -47,28 +38,9 @@
 #endif
 }
 
-/* Cache method IDs each time the class is loaded. */
-
 static void
 nativeClassInit(JNIEnv *_env, jclass glImplClass)
 {
-    jclass nioAccessClassLocal = _env->FindClass("java/nio/NIOAccess");
-    nioAccessClass = (jclass) _env->NewGlobalRef(nioAccessClassLocal);
-
-    jclass bufferClassLocal = _env->FindClass("java/nio/Buffer");
-    bufferClass = (jclass) _env->NewGlobalRef(bufferClassLocal);
-
-    getBasePointerID = _env->GetStaticMethodID(nioAccessClass,
-            "getBasePointer", "(Ljava/nio/Buffer;)J");
-    getBaseArrayID = _env->GetStaticMethodID(nioAccessClass,
-            "getBaseArray", "(Ljava/nio/Buffer;)Ljava/lang/Object;");
-    getBaseArrayOffsetID = _env->GetStaticMethodID(nioAccessClass,
-            "getBaseArrayOffset", "(Ljava/nio/Buffer;)I");
-
-    positionID = _env->GetFieldID(bufferClass, "position", "I");
-    limitID = _env->GetFieldID(bufferClass, "limit", "I");
-    elementSizeShiftID =
-        _env->GetFieldID(bufferClass, "_elementSizeShift", "I");
 }
 
 static void *
@@ -79,23 +51,17 @@
     jint elementSizeShift;
     jlong pointer;
 
-    position = _env->GetIntField(buffer, positionID);
-    limit = _env->GetIntField(buffer, limitID);
-    elementSizeShift = _env->GetIntField(buffer, elementSizeShiftID);
+    pointer = jniGetNioBufferFields(_env, buffer, &position, &limit, &elementSizeShift);
     *remaining = (limit - position) << elementSizeShift;
-    pointer = _env->CallStaticLongMethod(nioAccessClass,
-            getBasePointerID, buffer);
     if (pointer != 0L) {
-        *array = NULL;
+        *array = nullptr;
+        pointer += position << elementSizeShift;
         return reinterpret_cast<void*>(pointer);
     }
 
-    *array = (jarray) _env->CallStaticObjectMethod(nioAccessClass,
-            getBaseArrayID, buffer);
-    *offset = _env->CallStaticIntMethod(nioAccessClass,
-            getBaseArrayOffsetID, buffer);
-
-    return NULL;
+    *array = jniGetNioBufferBaseArray(_env, buffer);
+    *offset = jniGetNioBufferBaseArrayOffset(_env, buffer);
+    return nullptr;
 }
 
 class ByteArrayGetter {
@@ -217,16 +183,18 @@
 
 static void *
 getDirectBufferPointer(JNIEnv *_env, jobject buffer) {
-    char* buf = (char*) _env->GetDirectBufferAddress(buffer);
-    if (buf) {
-        jint position = _env->GetIntField(buffer, positionID);
-        jint elementSizeShift = _env->GetIntField(buffer, elementSizeShiftID);
-        buf += position << elementSizeShift;
-    } else {
+    jint position;
+    jint limit;
+    jint elementSizeShift;
+    jlong pointer;
+    pointer = jniGetNioBufferFields(_env, buffer, &position, &limit, &elementSizeShift);
+    if (pointer == 0) {
         jniThrowException(_env, "java/lang/IllegalArgumentException",
                           "Must use a native order direct Buffer");
+        return nullptr;
     }
-    return (void*) buf;
+    pointer += position << elementSizeShift;
+    return reinterpret_cast<void*>(pointer);
 }
 
 // --------------------------------------------------------------------------
diff --git a/opengl/tools/glgen/stubs/jsr239/GLCHeader.cpp b/opengl/tools/glgen/stubs/jsr239/GLCHeader.cpp
index c808fe9..c12efc3 100644
--- a/opengl/tools/glgen/stubs/jsr239/GLCHeader.cpp
+++ b/opengl/tools/glgen/stubs/jsr239/GLCHeader.cpp
@@ -64,16 +64,7 @@
         GLsizei stride, const GLvoid *pointer, GLsizei count);
 }
 
-static jclass nioAccessClass;
-static jclass bufferClass;
 static jclass G11ImplClass;
-static jmethodID getBasePointerID;
-static jmethodID getBaseArrayID;
-static jmethodID getBaseArrayOffsetID;
-static jmethodID allowIndirectBuffersID;
-static jfieldID positionID;
-static jfieldID limitID;
-static jfieldID elementSizeShiftID;
 static jfieldID haveCheckedExtensionsID;
 static jfieldID have_OES_blend_equation_separateID;
 static jfieldID have_OES_blend_subtractID;
@@ -85,12 +76,6 @@
 static void
 nativeClassInit(JNIEnv *_env, jclass glImplClass)
 {
-    jclass nioAccessClassLocal = _env->FindClass("java/nio/NIOAccess");
-    nioAccessClass = (jclass) _env->NewGlobalRef(nioAccessClassLocal);
-
-    jclass bufferClassLocal = _env->FindClass("java/nio/Buffer");
-    bufferClass = (jclass) _env->NewGlobalRef(bufferClassLocal);
-
     jclass g11impClassLocal = _env->FindClass("com/google/android/gles_jni/GLImpl");
     G11ImplClass = (jclass) _env->NewGlobalRef(g11impClassLocal);
     haveCheckedExtensionsID =  _env->GetFieldID(G11ImplClass, "haveCheckedExtensions", "Z");
@@ -98,19 +83,6 @@
     have_OES_blend_subtractID =  _env->GetFieldID(G11ImplClass, "have_OES_blend_subtract", "Z");
     have_OES_framebuffer_objectID =  _env->GetFieldID(G11ImplClass, "have_OES_framebuffer_object", "Z");
     have_OES_texture_cube_mapID =  _env->GetFieldID(G11ImplClass, "have_OES_texture_cube_map", "Z");
-
-    getBasePointerID = _env->GetStaticMethodID(nioAccessClass,
-            "getBasePointer", "(Ljava/nio/Buffer;)J");
-    getBaseArrayID = _env->GetStaticMethodID(nioAccessClass,
-            "getBaseArray", "(Ljava/nio/Buffer;)Ljava/lang/Object;");
-    getBaseArrayOffsetID = _env->GetStaticMethodID(nioAccessClass,
-            "getBaseArrayOffset", "(Ljava/nio/Buffer;)I");
-    allowIndirectBuffersID = _env->GetStaticMethodID(g11impClassLocal,
-            "allowIndirectBuffers", "(Ljava/lang/String;)Z");
-    positionID = _env->GetFieldID(bufferClass, "position", "I");
-    limitID = _env->GetFieldID(bufferClass, "limit", "I");
-    elementSizeShiftID =
-        _env->GetFieldID(bufferClass, "_elementSizeShift", "I");
 }
 
 static void *
@@ -121,28 +93,17 @@
     jint elementSizeShift;
     jlong pointer;
 
-    position = _env->GetIntField(buffer, positionID);
-    limit = _env->GetIntField(buffer, limitID);
-    elementSizeShift = _env->GetIntField(buffer, elementSizeShiftID);
+    pointer = jniGetNioBufferFields(_env, buffer, &position, &limit, &elementSizeShift);
     *remaining = (limit - position) << elementSizeShift;
-    pointer = _env->CallStaticLongMethod(nioAccessClass,
-            getBasePointerID, buffer);
     if (pointer != 0L) {
-        *offset = 0;
-        *array = NULL;
-        return reinterpret_cast<void *>(pointer);
+        *array = nullptr;
+        pointer += position << elementSizeShift;
+        return reinterpret_cast<void*>(pointer);
     }
 
-    *array = (jarray) _env->CallStaticObjectMethod(nioAccessClass,
-            getBaseArrayID, buffer);
-    if (*array == NULL) {
-        *offset = 0;
-        return (void*) NULL;
-    }
-    *offset = _env->CallStaticIntMethod(nioAccessClass,
-            getBaseArrayOffsetID, buffer);
-
-    return NULL;
+    *array = jniGetNioBufferBaseArray(_env, buffer);
+    *offset = jniGetNioBufferBaseArrayOffset(_env, buffer);
+    return nullptr;
 }
 
 static void
@@ -156,42 +117,24 @@
 extern char*  __progname;
 }
 
-static bool
-allowIndirectBuffers(JNIEnv *_env) {
-    static jint sIndirectBufferCompatability;
-    if (sIndirectBufferCompatability == 0) {
-        jobject appName = _env->NewStringUTF(::__progname);
-        sIndirectBufferCompatability = _env->CallStaticBooleanMethod(G11ImplClass, allowIndirectBuffersID, appName) ? 2 : 1;
-    }
-    return sIndirectBufferCompatability == 2;
-}
-
 static void *
 getDirectBufferPointer(JNIEnv *_env, jobject buffer) {
-    if (!buffer) {
-        return NULL;
+    if (buffer == nullptr) {
+        return nullptr;
     }
-    void* buf = _env->GetDirectBufferAddress(buffer);
-    if (buf) {
-        jint position = _env->GetIntField(buffer, positionID);
-        jint elementSizeShift = _env->GetIntField(buffer, elementSizeShiftID);
-        buf = ((char*) buf) + (position << elementSizeShift);
-    } else {
-        if (allowIndirectBuffers(_env)) {
-            jarray array = 0;
-            jint remaining;
-            jint offset;
-            buf = getPointer(_env, buffer, &array, &remaining, &offset);
-            if (array) {
-                releasePointer(_env, array, buf, 0);
-            }
-            buf = (char*)buf + offset;
-        } else {
-            jniThrowException(_env, "java/lang/IllegalArgumentException",
-                              "Must use a native order direct Buffer");
-        }
+
+    jint position;
+    jint limit;
+    jint elementSizeShift;
+    jlong pointer;
+    pointer = jniGetNioBufferFields(_env, buffer, &position, &limit, &elementSizeShift);
+    if (pointer == 0) {
+        jniThrowException(_env, "java/lang/IllegalArgumentException",
+                          "Must use a native order direct Buffer");
+        return nullptr;
     }
-    return buf;
+    pointer += position << elementSizeShift;
+    return reinterpret_cast<void*>(pointer);
 }
 
 static int
diff --git a/services/sensorservice/SensorDevice.cpp b/services/sensorservice/SensorDevice.cpp
index a6ed75f..6570704 100644
--- a/services/sensorservice/SensorDevice.cpp
+++ b/services/sensorservice/SensorDevice.cpp
@@ -579,10 +579,9 @@
         }
 
         if (info.batchParams.indexOfKey(ident) >= 0) {
-          if (info.numActiveClients() == 1) {
-              // This is the first connection, we need to activate the underlying h/w sensor.
-              actuateHardware = true;
-          }
+            if (info.numActiveClients() > 0 && !info.isActive) {
+                actuateHardware = true;
+            }
         } else {
             // Log error. Every activate call should be preceded by a batch() call.
             ALOGE("\t >>>ERROR: activate called without batch");
@@ -631,6 +630,11 @@
         if (err != NO_ERROR && enabled) {
             // Failure when enabling the sensor. Clean up on failure.
             info.removeBatchParamsForIdent(ident);
+        } else {
+            // Update the isActive flag if there is no error. If there is an error when disabling a
+            // sensor, still set the flag to false since the batch parameters have already been
+            // removed. This ensures that everything remains in-sync.
+            info.isActive = enabled;
         }
     }
 
diff --git a/services/sensorservice/SensorDevice.h b/services/sensorservice/SensorDevice.h
index 71b918f..e8685c2 100644
--- a/services/sensorservice/SensorDevice.h
+++ b/services/sensorservice/SensorDevice.h
@@ -165,6 +165,9 @@
         // requested by the client.
         KeyedVector<void*, BatchParams> batchParams;
 
+        // Flag to track if the sensor is active
+        bool isActive = false;
+
         // Sets batch parameters for this ident. Returns error if this ident is not already present
         // in the KeyedVector above.
         status_t setBatchParamsForIdent(void* ident, int flags, int64_t samplingPeriodNs,
diff --git a/services/sensorservice/SensorService.cpp b/services/sensorservice/SensorService.cpp
index e3dfde4..cbdd473 100644
--- a/services/sensorservice/SensorService.cpp
+++ b/services/sensorservice/SensorService.cpp
@@ -565,11 +565,11 @@
     if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
         return BAD_VALUE;
     }
-    if (args.size() == 3 && args[0] == String16("set-uid-state")) {
+    if (args[0] == String16("set-uid-state")) {
         return handleSetUidState(args, err);
-    } else if (args.size() == 2 && args[0] == String16("reset-uid-state")) {
+    } else if (args[0] == String16("reset-uid-state")) {
         return handleResetUidState(args, err);
-    } else if (args.size() == 2 && args[0] == String16("get-uid-state")) {
+    } else if (args[0] == String16("get-uid-state")) {
         return handleGetUidState(args, out, err);
     } else if (args.size() == 1 && args[0] == String16("help")) {
         printHelp(out);
@@ -579,14 +579,32 @@
     return BAD_VALUE;
 }
 
-status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
+static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
     PermissionController pc;
-    int uid = pc.getPackageUid(args[1], 0);
+    uid = pc.getPackageUid(packageName, 0);
     if (uid <= 0) {
-        ALOGE("Unknown package: '%s'", String8(args[1]).string());
-        dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
+        ALOGE("Unknown package: '%s'", String8(packageName).string());
+        dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
         return BAD_VALUE;
     }
+
+    if (userId < 0) {
+        ALOGE("Invalid user: %d", userId);
+        dprintf(err, "Invalid user: %d\n", userId);
+        return BAD_VALUE;
+    }
+
+    uid = multiuser_get_uid(userId, uid);
+    return NO_ERROR;
+}
+
+status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
+    // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
+    if (!(args.size() == 3 || args.size() == 5)) {
+        printHelp(err);
+        return BAD_VALUE;
+    }
+
     bool active = false;
     if (args[2] == String16("active")) {
         active = true;
@@ -594,30 +612,59 @@
         ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
         return BAD_VALUE;
     }
+
+    int userId = 0;
+    if (args.size() == 5 && args[3] == String16("--user")) {
+        userId = atoi(String8(args[4]));
+    }
+
+    uid_t uid;
+    if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
+        return BAD_VALUE;
+    }
+
     mUidPolicy->addOverrideUid(uid, active);
     return NO_ERROR;
 }
 
 status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
-    PermissionController pc;
-    int uid = pc.getPackageUid(args[1], 0);
-    if (uid < 0) {
-        ALOGE("Unknown package: '%s'", String8(args[1]).string());
-        dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
+    // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
+    if (!(args.size() == 2 || args.size() == 4)) {
+        printHelp(err);
         return BAD_VALUE;
     }
+
+    int userId = 0;
+    if (args.size() == 4 && args[2] == String16("--user")) {
+        userId = atoi(String8(args[3]));
+    }
+
+    uid_t uid;
+    if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
+        return BAD_VALUE;
+    }
+
     mUidPolicy->removeOverrideUid(uid);
     return NO_ERROR;
 }
 
 status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
-    PermissionController pc;
-    int uid = pc.getPackageUid(args[1], 0);
-    if (uid < 0) {
-        ALOGE("Unknown package: '%s'", String8(args[1]).string());
-        dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
+    // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
+    if (!(args.size() == 2 || args.size() == 4)) {
+        printHelp(err);
         return BAD_VALUE;
     }
+
+    int userId = 0;
+    if (args.size() == 4 && args[2] == String16("--user")) {
+        userId = atoi(String8(args[3]));
+    }
+
+    uid_t uid;
+    if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
+        return BAD_VALUE;
+    }
+
     if (mUidPolicy->isUidActive(uid)) {
         return dprintf(out, "active\n");
     } else {
@@ -627,9 +674,9 @@
 
 status_t SensorService::printHelp(int out) {
     return dprintf(out, "Sensor service commands:\n"
-        "  get-uid-state <PACKAGE> gets the uid state\n"
-        "  set-uid-state <PACKAGE> <active|idle> overrides the uid state\n"
-        "  reset-uid-state <PACKAGE> clears the uid state override\n"
+        "  get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
+        "  set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
+        "  reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
         "  help print this message\n");
 }
 
diff --git a/services/sensorservice/SensorService.h b/services/sensorservice/SensorService.h
index fbfe05d..5076967 100644
--- a/services/sensorservice/SensorService.h
+++ b/services/sensorservice/SensorService.h
@@ -23,6 +23,7 @@
 #include <binder/BinderService.h>
 #include <binder/IUidObserver.h>
 #include <cutils/compiler.h>
+#include <cutils/multiuser.h>
 #include <sensor/ISensorServer.h>
 #include <sensor/ISensorEventConnection.h>
 #include <sensor/Sensor.h>
diff --git a/services/surfaceflinger/Client.cpp b/services/surfaceflinger/Client.cpp
index 508be13..e54b460 100644
--- a/services/surfaceflinger/Client.cpp
+++ b/services/surfaceflinger/Client.cpp
@@ -76,9 +76,18 @@
                                uint32_t flags, const sp<IBinder>& parentHandle,
                                LayerMetadata metadata, sp<IBinder>* handle,
                                sp<IGraphicBufferProducer>* gbp) {
+    sp<Layer> parent = nullptr;
+    if (parentHandle != nullptr) {
+        auto layerHandle = reinterpret_cast<Layer::Handle*>(parentHandle.get());
+        parent = layerHandle->owner.promote();
+        if (parent == nullptr) {
+            return NAME_NOT_FOUND;
+        }
+    }
+
     // We rely on createLayer to check permissions.
     return mFlinger->createLayer(name, this, w, h, format, flags, std::move(metadata), handle, gbp,
-                                 parentHandle);
+                                 &parent);
 }
 
 status_t Client::createWithSurfaceParent(const String8& name, uint32_t w, uint32_t h,
diff --git a/services/surfaceflinger/CompositionEngine/Android.bp b/services/surfaceflinger/CompositionEngine/Android.bp
index e86d35d..6f076ad 100644
--- a/services/surfaceflinger/CompositionEngine/Android.bp
+++ b/services/surfaceflinger/CompositionEngine/Android.bp
@@ -68,6 +68,7 @@
         "mock/DisplaySurface.cpp",
         "mock/Layer.cpp",
         "mock/LayerFE.cpp",
+        "mock/NativeWindow.cpp",
         "mock/Output.cpp",
         "mock/OutputLayer.cpp",
         "mock/RenderSurface.cpp",
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/NativeWindow.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/NativeWindow.h
new file mode 100644
index 0000000..714d2f7
--- /dev/null
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/NativeWindow.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <gmock/gmock.h>
+#include <system/window.h>
+#include <ui/ANativeObjectBase.h>
+#include <ui/GraphicTypes.h>
+#include <ui/PixelFormat.h>
+
+namespace android::compositionengine::mock {
+
+/* ------------------------------------------------------------------------
+ * Mock NativeWindow
+ *
+ * An intentionally simplified Mock which implements a minimal subset of the full
+ * ANativeWindow interface.
+ */
+class NativeWindow : public ANativeObjectBase<ANativeWindow, NativeWindow, RefBase> {
+public:
+    NativeWindow();
+    ~NativeWindow();
+
+    MOCK_METHOD1(setSwapInterval, int(int));
+    MOCK_METHOD2(dequeueBuffer, int(struct ANativeWindowBuffer**, int*));
+    MOCK_METHOD2(cancelBuffer, int(struct ANativeWindowBuffer*, int));
+    MOCK_METHOD2(queueBuffer, int(struct ANativeWindowBuffer*, int));
+    MOCK_CONST_METHOD2(query, int(int, int*));
+    MOCK_METHOD1(connect, int(int));
+    MOCK_METHOD1(disconnect, int(int));
+    MOCK_METHOD1(lockBuffer_DEPRECATED, int(struct ANativeWindowBuffer*));
+    MOCK_METHOD1(setBuffersFormat, int(PixelFormat));
+    MOCK_METHOD1(setBuffersDataSpace, int(ui::Dataspace));
+    MOCK_METHOD1(setUsage, int(uint64_t));
+};
+
+} // namespace android::compositionengine::mock
diff --git a/services/surfaceflinger/CompositionEngine/mock/NativeWindow.cpp b/services/surfaceflinger/CompositionEngine/mock/NativeWindow.cpp
new file mode 100644
index 0000000..d0cc8ef
--- /dev/null
+++ b/services/surfaceflinger/CompositionEngine/mock/NativeWindow.cpp
@@ -0,0 +1,121 @@
+
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "compositionengine/mock/NativeWindow.h"
+#include <log/log.h>
+
+namespace android::compositionengine::mock {
+
+static int forwardSetSwapInterval(ANativeWindow* window, int interval) {
+    return static_cast<NativeWindow*>(window)->setSwapInterval(interval);
+}
+
+static int forwardDequeueBuffer(ANativeWindow* window, ANativeWindowBuffer** buffer, int* fenceFd) {
+    return static_cast<NativeWindow*>(window)->dequeueBuffer(buffer, fenceFd);
+}
+
+static int forwardCancelBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd) {
+    return static_cast<NativeWindow*>(window)->cancelBuffer(buffer, fenceFd);
+}
+
+static int forwardQueueBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd) {
+    return static_cast<NativeWindow*>(window)->queueBuffer(buffer, fenceFd);
+}
+
+static int forwardQuery(const ANativeWindow* window, int what, int* value) {
+    return static_cast<const NativeWindow*>(window)->query(what, value);
+}
+
+static int forwardPerform(ANativeWindow* window, int operation, ...) {
+    va_list args;
+    va_start(args, operation);
+    int result = NO_ERROR;
+    switch (operation) {
+        case NATIVE_WINDOW_API_CONNECT: {
+            int api = va_arg(args, int);
+            result = static_cast<NativeWindow*>(window)->connect(api);
+            break;
+        }
+        case NATIVE_WINDOW_SET_BUFFERS_FORMAT: {
+            PixelFormat format = va_arg(args, PixelFormat);
+            result = static_cast<NativeWindow*>(window)->setBuffersFormat(format);
+            break;
+        }
+        case NATIVE_WINDOW_SET_BUFFERS_DATASPACE: {
+            ui::Dataspace dataspace = static_cast<ui::Dataspace>(va_arg(args, int));
+            result = static_cast<NativeWindow*>(window)->setBuffersDataSpace(dataspace);
+            break;
+        }
+        case NATIVE_WINDOW_SET_USAGE: {
+            // Note: Intentionally widens usage from 32 to 64 bits so we
+            // just have one implementation.
+            uint64_t usage = va_arg(args, uint32_t);
+            result = static_cast<NativeWindow*>(window)->setUsage(usage);
+            break;
+        }
+        case NATIVE_WINDOW_SET_USAGE64: {
+            uint64_t usage = va_arg(args, uint64_t);
+            result = static_cast<NativeWindow*>(window)->setUsage(usage);
+            break;
+        }
+        case NATIVE_WINDOW_API_DISCONNECT: {
+            int api = va_arg(args, int);
+            result = static_cast<NativeWindow*>(window)->disconnect(api);
+            break;
+        }
+        default:
+            LOG_ALWAYS_FATAL("Unexpected operation %d", operation);
+            break;
+    }
+
+    va_end(args);
+    return result;
+}
+
+static int forwardDequeueBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer** buffer) {
+    int ignoredFenceFd = -1;
+    return static_cast<NativeWindow*>(window)->dequeueBuffer(buffer, &ignoredFenceFd);
+}
+
+static int forwardCancelBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer* buffer) {
+    return static_cast<NativeWindow*>(window)->cancelBuffer(buffer, -1);
+}
+
+static int forwardLockBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer* buffer) {
+    return static_cast<NativeWindow*>(window)->lockBuffer_DEPRECATED(buffer);
+}
+
+static int forwardQueueBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer* buffer) {
+    return static_cast<NativeWindow*>(window)->queueBuffer(buffer, -1);
+}
+
+NativeWindow::NativeWindow() {
+    ANativeWindow::setSwapInterval = &forwardSetSwapInterval;
+    ANativeWindow::dequeueBuffer = &forwardDequeueBuffer;
+    ANativeWindow::cancelBuffer = &forwardCancelBuffer;
+    ANativeWindow::queueBuffer = &forwardQueueBuffer;
+    ANativeWindow::query = &forwardQuery;
+    ANativeWindow::perform = &forwardPerform;
+
+    ANativeWindow::dequeueBuffer_DEPRECATED = &forwardDequeueBufferDeprecated;
+    ANativeWindow::cancelBuffer_DEPRECATED = &forwardCancelBufferDeprecated;
+    ANativeWindow::lockBuffer_DEPRECATED = &forwardLockBufferDeprecated;
+    ANativeWindow::queueBuffer_DEPRECATED = &forwardQueueBufferDeprecated;
+}
+NativeWindow::~NativeWindow() = default;
+
+} // namespace android::compositionengine::mock
diff --git a/services/surfaceflinger/CompositionEngine/src/RenderSurface.cpp b/services/surfaceflinger/CompositionEngine/src/RenderSurface.cpp
index b4dfba1..b5a6678 100644
--- a/services/surfaceflinger/CompositionEngine/src/RenderSurface.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/RenderSurface.cpp
@@ -52,9 +52,14 @@
         mDisplay(display),
         mNativeWindow(args.nativeWindow),
         mDisplaySurface(args.displaySurface),
-        mSize(args.displayWidth, args.displayHeight) {}
+        mSize(args.displayWidth, args.displayHeight) {
+    LOG_ALWAYS_FATAL_IF(!mNativeWindow);
+}
 
-RenderSurface::~RenderSurface() = default;
+RenderSurface::~RenderSurface() {
+    ANativeWindow* const window = mNativeWindow.get();
+    native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
+}
 
 bool RenderSurface::isValid() const {
     return mSize.isValid();
diff --git a/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp b/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
index cd2d454..33444a5 100644
--- a/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
@@ -22,9 +22,9 @@
 #include <compositionengine/RenderSurfaceCreationArgs.h>
 #include <compositionengine/impl/Display.h>
 #include <compositionengine/mock/CompositionEngine.h>
+#include <compositionengine/mock/NativeWindow.h>
 #include <compositionengine/mock/RenderSurface.h>
 #include <gtest/gtest.h>
-#include <system/window.h>
 
 #include "MockHWComposer.h"
 
@@ -43,6 +43,7 @@
 
     StrictMock<android::mock::HWComposer> mHwComposer;
     StrictMock<mock::CompositionEngine> mCompositionEngine;
+    sp<mock::NativeWindow> mNativeWindow = new StrictMock<mock::NativeWindow>();
     impl::Display mDisplay{mCompositionEngine,
                            DisplayCreationArgsBuilder().setDisplayId(DEFAULT_DISPLAY_ID).build()};
 };
@@ -199,8 +200,9 @@
  */
 
 TEST_F(DisplayTest, createRenderSurfaceSetsRenderSurface) {
+    EXPECT_CALL(*mNativeWindow, disconnect(NATIVE_WINDOW_API_EGL)).WillRepeatedly(Return(NO_ERROR));
     EXPECT_TRUE(mDisplay.getRenderSurface() == nullptr);
-    mDisplay.createRenderSurface(RenderSurfaceCreationArgs{640, 480, nullptr, nullptr});
+    mDisplay.createRenderSurface(RenderSurfaceCreationArgs{640, 480, mNativeWindow, nullptr});
     EXPECT_TRUE(mDisplay.getRenderSurface() != nullptr);
 }
 
diff --git a/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp b/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp
index 84af9b9..9960478 100644
--- a/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp
@@ -22,11 +22,10 @@
 #include <compositionengine/mock/CompositionEngine.h>
 #include <compositionengine/mock/Display.h>
 #include <compositionengine/mock/DisplaySurface.h>
+#include <compositionengine/mock/NativeWindow.h>
 #include <compositionengine/mock/OutputLayer.h>
 #include <gtest/gtest.h>
 #include <renderengine/mock/RenderEngine.h>
-#include <system/window.h>
-#include <ui/ANativeObjectBase.h>
 
 #include "MockHWComposer.h"
 
@@ -34,123 +33,6 @@
 namespace {
 
 /* ------------------------------------------------------------------------
- * MockNativeWindow
- *
- * An intentionally simplified Mock which implements a minimal subset of the full
- * ANativeWindow interface.
- */
-
-class MockNativeWindow : public ANativeObjectBase<ANativeWindow, MockNativeWindow, RefBase> {
-public:
-    MockNativeWindow() {
-        ANativeWindow::setSwapInterval = &forwardSetSwapInterval;
-        ANativeWindow::dequeueBuffer = &forwardDequeueBuffer;
-        ANativeWindow::cancelBuffer = &forwardCancelBuffer;
-        ANativeWindow::queueBuffer = &forwardQueueBuffer;
-        ANativeWindow::query = &forwardQuery;
-        ANativeWindow::perform = &forwardPerform;
-
-        ANativeWindow::dequeueBuffer_DEPRECATED = &forwardDequeueBufferDeprecated;
-        ANativeWindow::cancelBuffer_DEPRECATED = &forwardCancelBufferDeprecated;
-        ANativeWindow::lockBuffer_DEPRECATED = &forwardLockBufferDeprecated;
-        ANativeWindow::queueBuffer_DEPRECATED = &forwardQueueBufferDeprecated;
-    }
-
-    MOCK_METHOD1(setSwapInterval, int(int));
-    MOCK_METHOD2(dequeueBuffer, int(struct ANativeWindowBuffer**, int*));
-    MOCK_METHOD2(cancelBuffer, int(struct ANativeWindowBuffer*, int));
-    MOCK_METHOD2(queueBuffer, int(struct ANativeWindowBuffer*, int));
-    MOCK_CONST_METHOD2(query, int(int, int*));
-    MOCK_METHOD1(connect, int(int));
-    MOCK_METHOD1(lockBuffer_DEPRECATED, int(struct ANativeWindowBuffer*));
-    MOCK_METHOD1(setBuffersFormat, int(PixelFormat));
-    MOCK_METHOD1(setBuffersDataSpace, int(ui::Dataspace));
-    MOCK_METHOD1(setUsage, int(uint64_t));
-
-    static void unexpectedCall(...) { LOG_ALWAYS_FATAL("Unexpected ANativeWindow API call"); }
-
-    static int forwardSetSwapInterval(ANativeWindow* window, int interval) {
-        return getSelf(window)->setSwapInterval(interval);
-    }
-
-    static int forwardDequeueBuffer(ANativeWindow* window, ANativeWindowBuffer** buffer,
-                                    int* fenceFd) {
-        return getSelf(window)->dequeueBuffer(buffer, fenceFd);
-    }
-
-    static int forwardCancelBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer,
-                                   int fenceFd) {
-        return getSelf(window)->cancelBuffer(buffer, fenceFd);
-    }
-
-    static int forwardQueueBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd) {
-        return getSelf(window)->queueBuffer(buffer, fenceFd);
-    }
-
-    static int forwardQuery(const ANativeWindow* window, int what, int* value) {
-        return getSelf(window)->query(what, value);
-    }
-
-    static int forwardPerform(ANativeWindow* window, int operation, ...) {
-        va_list args;
-        va_start(args, operation);
-        int result = NO_ERROR;
-        switch (operation) {
-            case NATIVE_WINDOW_API_CONNECT: {
-                int api = va_arg(args, int);
-                result = getSelf(window)->connect(api);
-                break;
-            }
-            case NATIVE_WINDOW_SET_BUFFERS_FORMAT: {
-                PixelFormat format = va_arg(args, PixelFormat);
-                result = getSelf(window)->setBuffersFormat(format);
-                break;
-            }
-            case NATIVE_WINDOW_SET_BUFFERS_DATASPACE: {
-                ui::Dataspace dataspace = static_cast<ui::Dataspace>(va_arg(args, int));
-                result = getSelf(window)->setBuffersDataSpace(dataspace);
-                break;
-            }
-            case NATIVE_WINDOW_SET_USAGE: {
-                // Note: Intentionally widens usage from 32 to 64 bits so we
-                // just have one implementation.
-                uint64_t usage = va_arg(args, uint32_t);
-                result = getSelf(window)->setUsage(usage);
-                break;
-            }
-            case NATIVE_WINDOW_SET_USAGE64: {
-                uint64_t usage = va_arg(args, uint64_t);
-                result = getSelf(window)->setUsage(usage);
-                break;
-            }
-            default:
-                LOG_ALWAYS_FATAL("Unexpected operation %d", operation);
-                break;
-        }
-
-        va_end(args);
-        return result;
-    }
-
-    static int forwardDequeueBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer** buffer) {
-        int ignoredFenceFd = -1;
-        return getSelf(window)->dequeueBuffer(buffer, &ignoredFenceFd);
-    }
-
-    static int forwardCancelBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer* buffer) {
-        return getSelf(window)->cancelBuffer(buffer, -1);
-    }
-
-    static int forwardLockBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer* buffer) {
-        return getSelf(window)->lockBuffer_DEPRECATED(buffer);
-    }
-
-    static int forwardQueueBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer* buffer) {
-        return getSelf(window)->queueBuffer(buffer, -1);
-    }
-};
-
-/* ------------------------------------------------------------------------
  * RenderSurfaceTest
  */
 
@@ -175,6 +57,8 @@
         EXPECT_CALL(mDisplay, getName()).WillRepeatedly(ReturnRef(DEFAULT_DISPLAY_NAME));
         EXPECT_CALL(mCompositionEngine, getHwComposer).WillRepeatedly(ReturnRef(mHwComposer));
         EXPECT_CALL(mCompositionEngine, getRenderEngine).WillRepeatedly(ReturnRef(mRenderEngine));
+        EXPECT_CALL(*mNativeWindow, disconnect(NATIVE_WINDOW_API_EGL))
+                .WillRepeatedly(Return(NO_ERROR));
     }
     ~RenderSurfaceTest() override = default;
 
@@ -182,7 +66,7 @@
     StrictMock<renderengine::mock::RenderEngine> mRenderEngine;
     StrictMock<mock::CompositionEngine> mCompositionEngine;
     StrictMock<mock::Display> mDisplay;
-    sp<MockNativeWindow> mNativeWindow = new StrictMock<MockNativeWindow>();
+    sp<mock::NativeWindow> mNativeWindow = new StrictMock<mock::NativeWindow>();
     sp<mock::DisplaySurface> mDisplaySurface = new StrictMock<mock::DisplaySurface>();
     impl::RenderSurface mSurface{mCompositionEngine, mDisplay,
                                  RenderSurfaceCreationArgs{DEFAULT_DISPLAY_WIDTH,
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index 0211df9..1527c34 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -130,6 +130,7 @@
     }
 
     mFrameTracker.logAndResetStats(mName);
+
     mFlinger->onLayerDestroyed();
 }
 
@@ -1229,10 +1230,8 @@
 
 void Layer::updateTransformHint(const sp<const DisplayDevice>& display) const {
     uint32_t orientation = 0;
-    // Disable setting transform hint if the debug flag is set or if the
-    // getTransformToDisplayInverse flag is set and the client wants to submit buffers
-    // in one orientation.
-    if (!mFlinger->mDebugDisableTransformHint && !getTransformToDisplayInverse()) {
+    // Disable setting transform hint if the debug flag is set.
+    if (!mFlinger->mDebugDisableTransformHint) {
         // The transform hint is used to improve performance, but we can
         // only have a single transform hint, it cannot
         // apply to all displays.
diff --git a/services/surfaceflinger/MonitoredProducer.cpp b/services/surfaceflinger/MonitoredProducer.cpp
index 06e3d9c..c60421b 100644
--- a/services/surfaceflinger/MonitoredProducer.cpp
+++ b/services/surfaceflinger/MonitoredProducer.cpp
@@ -132,6 +132,10 @@
     return mProducer->setDequeueTimeout(timeout);
 }
 
+status_t MonitoredProducer::setLegacyBufferDrop(bool drop) {
+    return mProducer->setLegacyBufferDrop(drop);
+}
+
 status_t MonitoredProducer::getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer,
         sp<Fence>* outFence, float outTransformMatrix[16]) {
     return mProducer->getLastQueuedBuffer(outBuffer, outFence,
diff --git a/services/surfaceflinger/MonitoredProducer.h b/services/surfaceflinger/MonitoredProducer.h
index 1246d14..d346f82 100644
--- a/services/surfaceflinger/MonitoredProducer.h
+++ b/services/surfaceflinger/MonitoredProducer.h
@@ -61,6 +61,7 @@
     virtual status_t setGenerationNumber(uint32_t generationNumber);
     virtual String8 getConsumerName() const override;
     virtual status_t setDequeueTimeout(nsecs_t timeout) override;
+    virtual status_t setLegacyBufferDrop(bool drop) override;
     virtual status_t getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer,
             sp<Fence>* outFence, float outTransformMatrix[16]) override;
     virtual IBinder* onAsBinder();
diff --git a/services/surfaceflinger/RefreshRateOverlay.cpp b/services/surfaceflinger/RefreshRateOverlay.cpp
index 240c84e..e70bfe4 100644
--- a/services/surfaceflinger/RefreshRateOverlay.cpp
+++ b/services/surfaceflinger/RefreshRateOverlay.cpp
@@ -31,9 +31,9 @@
     const status_t ret =
             mFlinger.createLayer(String8("RefreshRateOverlay"), mClient, 0, 0,
                                  PIXEL_FORMAT_RGBA_8888, ISurfaceComposerClient::eFXSurfaceColor,
-                                 LayerMetadata(), &mIBinder, &mGbp, nullptr);
+                                 LayerMetadata(), &mIBinder, &mGbp, &mLayer);
     if (ret) {
-        ALOGE("failed to create color layer");
+        ALOGE("failed to color layer");
         return false;
     }
 
diff --git a/services/surfaceflinger/Scheduler/DispSync.cpp b/services/surfaceflinger/Scheduler/DispSync.cpp
index f72aef1..871f556 100644
--- a/services/surfaceflinger/Scheduler/DispSync.cpp
+++ b/services/surfaceflinger/Scheduler/DispSync.cpp
@@ -210,14 +210,16 @@
             const nsecs_t baseTime = now - mReferenceTime;
             const nsecs_t numPeriodsSinceReference = baseTime / mPeriod;
             const nsecs_t predictedReference = mReferenceTime + numPeriodsSinceReference * mPeriod;
-            const nsecs_t phaseCorrection = mPhase + listener.mPhase;
-            listener.mLastEventTime = predictedReference + phaseCorrection;
+            listener.mLastEventTime = predictedReference + mPhase + listener.mPhase;
             // If we're very close in time to the predicted last event time,
+            // and we're not very close to the next predicted last event time
             // then we need to back up the last event time so that we can
             // attempt to fire an event immediately.
             //
-            // Otherwise, keep the last event time that we predicted.
-            if (isShorterThanPeriod(now - listener.mLastEventTime)) {
+            // Otherwise, keep the last event time that we predicted so that
+            // we don't wake up early.
+            if (isShorterThanPeriod(now - listener.mLastEventTime) &&
+                !isShorterThanPeriod(listener.mLastEventTime + mPeriod - now)) {
                 listener.mLastEventTime -= mPeriod;
             }
         } else {
@@ -279,7 +281,6 @@
                 return NO_ERROR;
             }
         }
-
         return BAD_VALUE;
     }
 
@@ -525,21 +526,40 @@
     mNumResyncSamples = 0;
 }
 
-bool DispSync::addResyncSample(nsecs_t timestamp) {
+bool DispSync::addResyncSample(nsecs_t timestamp, bool* periodChanged) {
     Mutex::Autolock lock(mMutex);
 
     ALOGV("[%s] addResyncSample(%" PRId64 ")", mName, ns2us(timestamp));
 
-    size_t idx = (mFirstResyncSample + mNumResyncSamples) % MAX_RESYNC_SAMPLES;
+    *periodChanged = false;
+    const size_t idx = (mFirstResyncSample + mNumResyncSamples) % MAX_RESYNC_SAMPLES;
     mResyncSamples[idx] = timestamp;
     if (mNumResyncSamples == 0) {
         mPhase = 0;
-        mReferenceTime = timestamp;
         ALOGV("[%s] First resync sample: mPeriod = %" PRId64 ", mPhase = 0, "
               "mReferenceTime = %" PRId64,
-              mName, ns2us(mPeriod), ns2us(mReferenceTime));
-        mThread->updateModel(mPeriod, mPhase, mReferenceTime);
+              mName, ns2us(mPeriod), ns2us(timestamp));
+    } else if (mPendingPeriod > 0) {
+        // mNumResyncSamples > 0, so priorIdx won't overflow
+        const size_t priorIdx = (mFirstResyncSample + mNumResyncSamples - 1) % MAX_RESYNC_SAMPLES;
+        const nsecs_t lastTimestamp = mResyncSamples[priorIdx];
+
+        const nsecs_t observedVsync = std::abs(timestamp - lastTimestamp);
+        if (std::abs(observedVsync - mPendingPeriod) < std::abs(observedVsync - mPeriod)) {
+            // Observed vsync is closer to the pending period, so reset the
+            // model and flush the pending period.
+            resetLocked();
+            mPeriod = mPendingPeriod;
+            mPendingPeriod = 0;
+            if (mTraceDetailedInfo) {
+                ATRACE_INT("DispSync:PendingPeriod", mPendingPeriod);
+            }
+            *periodChanged = true;
+        }
     }
+    // Always update the reference time with the most recent timestamp.
+    mReferenceTime = timestamp;
+    mThread->updateModel(mPeriod, mPhase, mReferenceTime);
 
     if (mNumResyncSamples < MAX_RESYNC_SAMPLES) {
         mNumResyncSamples++;
@@ -562,7 +582,7 @@
 
     // Check against kErrorThreshold / 2 to add some hysteresis before having to
     // resync again
-    bool modelLocked = mModelUpdated && mError < (kErrorThreshold / 2);
+    bool modelLocked = mModelUpdated && mError < (kErrorThreshold / 2) && mPendingPeriod == 0;
     ALOGV("[%s] addResyncSample returning %s", mName, modelLocked ? "locked" : "unlocked");
     return !modelLocked;
 }
@@ -594,9 +614,10 @@
 
 void DispSync::setPeriod(nsecs_t period) {
     Mutex::Autolock lock(mMutex);
-    mPeriod = period;
-    mPhase = 0;
-    mThread->updateModel(mPeriod, mPhase, mReferenceTime);
+    if (mTraceDetailedInfo) {
+        ATRACE_INT("DispSync:PendingPeriod", period);
+    }
+    mPendingPeriod = period;
 }
 
 nsecs_t DispSync::getPeriod() {
diff --git a/services/surfaceflinger/Scheduler/DispSync.h b/services/surfaceflinger/Scheduler/DispSync.h
index de2b874..8f8b8e7 100644
--- a/services/surfaceflinger/Scheduler/DispSync.h
+++ b/services/surfaceflinger/Scheduler/DispSync.h
@@ -49,7 +49,7 @@
     virtual void reset() = 0;
     virtual bool addPresentFence(const std::shared_ptr<FenceTime>&) = 0;
     virtual void beginResync() = 0;
-    virtual bool addResyncSample(nsecs_t timestamp) = 0;
+    virtual bool addResyncSample(nsecs_t timestamp, bool* periodChanged) = 0;
     virtual void endResync() = 0;
     virtual void setPeriod(nsecs_t period) = 0;
     virtual nsecs_t getPeriod() = 0;
@@ -119,7 +119,13 @@
     // addPresentFence returns true indicating that the model has drifted away
     // from the hardware vsync events.
     void beginResync() override;
-    bool addResyncSample(nsecs_t timestamp) override;
+    // Adds a vsync sample to the dispsync model. The timestamp is the time
+    // of the vsync event that fired. periodChanged will return true if the
+    // vsync period was detected to have changed to mPendingPeriod.
+    //
+    // This method will return true if more vsync samples are needed to lock
+    // down the DispSync model, and false otherwise.
+    bool addResyncSample(nsecs_t timestamp, bool* periodChanged) override;
     void endResync() override;
 
     // The setPeriod method sets the vsync event model's period to a specific
@@ -199,6 +205,12 @@
     // nanoseconds.
     nsecs_t mPeriod;
 
+    // mPendingPeriod is the proposed period change in nanoseconds.
+    // If mPendingPeriod differs from mPeriod and is nonzero, it will
+    // be flushed to mPeriod when we detect that the hardware switched
+    // vsync frequency.
+    nsecs_t mPendingPeriod = 0;
+
     // mPhase is the phase offset of the modeled vsync events.  It is the
     // number of nanoseconds from time 0 to the first vsync event.
     nsecs_t mPhase;
diff --git a/services/surfaceflinger/Scheduler/DispSyncSource.cpp b/services/surfaceflinger/Scheduler/DispSyncSource.cpp
index 6e89648..00948ae 100644
--- a/services/surfaceflinger/Scheduler/DispSyncSource.cpp
+++ b/services/surfaceflinger/Scheduler/DispSyncSource.cpp
@@ -87,19 +87,7 @@
     }
 }
 
-void DispSyncSource::pauseVsyncCallback(bool pause) {
-    std::lock_guard lock(mVsyncMutex);
-    mCallbackPaused = pause;
-}
-
 void DispSyncSource::onDispSyncEvent(nsecs_t when) {
-    {
-        std::lock_guard lock(mVsyncMutex);
-        if (mCallbackPaused) {
-            return;
-        }
-    }
-
     VSyncSource::Callback* callback;
     {
         std::lock_guard lock(mCallbackMutex);
diff --git a/services/surfaceflinger/Scheduler/DispSyncSource.h b/services/surfaceflinger/Scheduler/DispSyncSource.h
index 2858678..4759699 100644
--- a/services/surfaceflinger/Scheduler/DispSyncSource.h
+++ b/services/surfaceflinger/Scheduler/DispSyncSource.h
@@ -33,7 +33,6 @@
     void setVSyncEnabled(bool enable) override;
     void setCallback(VSyncSource::Callback* callback) override;
     void setPhaseOffset(nsecs_t phaseOffset) override;
-    void pauseVsyncCallback(bool pause) override;
 
 private:
     // The following method is the implementation of the DispSync::Callback.
@@ -55,7 +54,6 @@
     std::mutex mVsyncMutex;
     nsecs_t mPhaseOffset GUARDED_BY(mVsyncMutex);
     bool mEnabled GUARDED_BY(mVsyncMutex) = false;
-    bool mCallbackPaused GUARDED_BY(mVsyncMutex) = false;
 };
 
 } // namespace android
\ No newline at end of file
diff --git a/services/surfaceflinger/Scheduler/EventThread.cpp b/services/surfaceflinger/Scheduler/EventThread.cpp
index a760079..a6c7e6c 100644
--- a/services/surfaceflinger/Scheduler/EventThread.cpp
+++ b/services/surfaceflinger/Scheduler/EventThread.cpp
@@ -210,12 +210,6 @@
     mVSyncSource->setPhaseOffset(phaseOffset);
 }
 
-void EventThread::pauseVsyncCallback(bool pause) {
-    std::lock_guard<std::mutex> lock(mMutex);
-    ATRACE_INT("vsyncPaused", pause);
-    mVSyncSource->pauseVsyncCallback(pause);
-}
-
 sp<EventThreadConnection> EventThread::createEventConnection(
         ResyncCallback resyncCallback, ResetIdleTimerCallback resetIdleTimerCallback) const {
     return new EventThreadConnection(const_cast<EventThread*>(this), std::move(resyncCallback),
diff --git a/services/surfaceflinger/Scheduler/EventThread.h b/services/surfaceflinger/Scheduler/EventThread.h
index 67e6de9..7107d63 100644
--- a/services/surfaceflinger/Scheduler/EventThread.h
+++ b/services/surfaceflinger/Scheduler/EventThread.h
@@ -66,9 +66,6 @@
     virtual void setVSyncEnabled(bool enable) = 0;
     virtual void setCallback(Callback* callback) = 0;
     virtual void setPhaseOffset(nsecs_t phaseOffset) = 0;
-
-    // pause/resume vsync callback generation
-    virtual void pauseVsyncCallback(bool pause) = 0;
 };
 
 class EventThreadConnection : public BnDisplayEventConnection {
@@ -125,8 +122,6 @@
     // Requests the next vsync. If resetIdleTimer is set to true, it resets the idle timer.
     virtual void requestNextVsync(const sp<EventThreadConnection>& connection,
                                   bool resetIdleTimer) = 0;
-
-    virtual void pauseVsyncCallback(bool pause) = 0;
 };
 
 namespace impl {
@@ -162,8 +157,6 @@
 
     void setPhaseOffset(nsecs_t phaseOffset) override;
 
-    void pauseVsyncCallback(bool pause) override;
-
 private:
     friend EventThreadTest;
 
diff --git a/services/surfaceflinger/Scheduler/PhaseOffsets.cpp b/services/surfaceflinger/Scheduler/PhaseOffsets.cpp
index 7e2b03d..16f6729 100644
--- a/services/surfaceflinger/Scheduler/PhaseOffsets.cpp
+++ b/services/surfaceflinger/Scheduler/PhaseOffsets.cpp
@@ -86,8 +86,9 @@
     mHighRefreshRateOffsets.late = {highFpsLateSfOffsetNs, highFpsLateAppOffsetNs};
 }
 
-PhaseOffsets::Offsets PhaseOffsets::getCurrentOffsets() const {
-    switch (mRefreshRateType) {
+PhaseOffsets::Offsets PhaseOffsets::getOffsetsForRefreshRate(
+        android::scheduler::RefreshRateConfigs::RefreshRateType refreshRateType) const {
+    switch (refreshRateType) {
         case RefreshRateConfigs::RefreshRateType::PERFORMANCE:
             return mHighRefreshRateOffsets;
         default:
diff --git a/services/surfaceflinger/Scheduler/PhaseOffsets.h b/services/surfaceflinger/Scheduler/PhaseOffsets.h
index cbcaade..08747a5 100644
--- a/services/surfaceflinger/Scheduler/PhaseOffsets.h
+++ b/services/surfaceflinger/Scheduler/PhaseOffsets.h
@@ -42,6 +42,8 @@
 
     virtual nsecs_t getCurrentAppOffset() = 0;
     virtual nsecs_t getCurrentSfOffset() = 0;
+    virtual Offsets getOffsetsForRefreshRate(
+            RefreshRateConfigs::RefreshRateType refreshRateType) const = 0;
     virtual Offsets getCurrentOffsets() const = 0;
     virtual void setRefreshRateType(RefreshRateConfigs::RefreshRateType refreshRateType) = 0;
     virtual void dump(std::string& result) const = 0;
@@ -55,8 +57,14 @@
     nsecs_t getCurrentAppOffset() override;
     nsecs_t getCurrentSfOffset() override;
 
+    // Returns early, early GL, and late offsets for Apps and SF for a given refresh rate.
+    Offsets getOffsetsForRefreshRate(
+            RefreshRateConfigs::RefreshRateType refreshRateType) const override;
+
     // Returns early, early GL, and late offsets for Apps and SF.
-    Offsets getCurrentOffsets() const override;
+    Offsets getCurrentOffsets() const override {
+        return getOffsetsForRefreshRate(mRefreshRateType);
+    }
 
     // This function should be called when the device is switching between different
     // refresh rates, to properly update the offsets.
@@ -68,8 +76,8 @@
     void dump(std::string& result) const override;
 
 private:
-    Offsets getmDefaultRefreshRateOffsets() { return mDefaultRefreshRateOffsets; }
-    Offsets getmHighRefreshRateOffsets() { return mHighRefreshRateOffsets; }
+    Offsets getDefaultRefreshRateOffsets() { return mDefaultRefreshRateOffsets; }
+    Offsets getHighRefreshRateOffsets() { return mHighRefreshRateOffsets; }
 
     std::atomic<RefreshRateConfigs::RefreshRateType> mRefreshRateType =
             RefreshRateConfigs::RefreshRateType::DEFAULT;
diff --git a/services/surfaceflinger/Scheduler/RefreshRateConfigs.h b/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
index eb9ae35..d730058 100644
--- a/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
+++ b/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
@@ -47,6 +47,8 @@
         std::string name;
         // Refresh rate in frames per second, rounded to the nearest integer.
         uint32_t fps = 0;
+        // config Id (returned from HWC2::Display::Config::getId())
+        hwc2_config_t id;
     };
 
     // TODO(b/122916473): Get this information from configs prepared by vendors, instead of
@@ -62,13 +64,24 @@
         return nullptr;
     }
 
+    RefreshRateType getRefreshRateType(hwc2_config_t id) const {
+        for (const auto& [type, refreshRate] : mRefreshRates) {
+            if (refreshRate->id == id) {
+                return type;
+            }
+        }
+
+        return RefreshRateType::DEFAULT;
+    }
+
     void populate(const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs) {
         mRefreshRates.clear();
 
         // This is the rate that HWC encapsulates right now when the device is in DOZE mode.
         mRefreshRates.emplace(RefreshRateType::POWER_SAVING,
                               std::make_shared<RefreshRate>(
-                                      RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0}));
+                                      RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0,
+                                                  HWC2_SCREEN_OFF_CONFIG_ID}));
 
         if (configs.size() < 1) {
             ALOGE("Device does not have valid configs. Config size is 0.");
@@ -91,11 +104,12 @@
         nsecs_t vsyncPeriod = configIdToVsyncPeriod[0].second;
         if (vsyncPeriod != 0) {
             const float fps = 1e9 / vsyncPeriod;
+            const int configId = configIdToVsyncPeriod[0].first;
             mRefreshRates.emplace(RefreshRateType::DEFAULT,
                                   std::make_shared<RefreshRate>(
-                                          RefreshRate{configIdToVsyncPeriod[0].first,
-                                                      base::StringPrintf("%2.ffps", fps),
-                                                      static_cast<uint32_t>(fps)}));
+                                          RefreshRate{configId, base::StringPrintf("%2.ffps", fps),
+                                                      static_cast<uint32_t>(fps),
+                                                      configs.at(configId)->getId()}));
         }
 
         if (configs.size() < 2) {
@@ -107,11 +121,12 @@
         vsyncPeriod = configIdToVsyncPeriod[1].second;
         if (vsyncPeriod != 0) {
             const float fps = 1e9 / vsyncPeriod;
+            const int configId = configIdToVsyncPeriod[1].first;
             mRefreshRates.emplace(RefreshRateType::PERFORMANCE,
                                   std::make_shared<RefreshRate>(
-                                          RefreshRate{configIdToVsyncPeriod[1].first,
-                                                      base::StringPrintf("%2.ffps", fps),
-                                                      static_cast<uint32_t>(fps)}));
+                                          RefreshRate{configId, base::StringPrintf("%2.ffps", fps),
+                                                      static_cast<uint32_t>(fps),
+                                                      configs.at(configId)->getId()}));
         }
     }
 
diff --git a/services/surfaceflinger/Scheduler/Scheduler.cpp b/services/surfaceflinger/Scheduler/Scheduler.cpp
index b1c39ef..1b154a4 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.cpp
+++ b/services/surfaceflinger/Scheduler/Scheduler.cpp
@@ -178,12 +178,6 @@
     mConnections[handle->id]->thread->setPhaseOffset(phaseOffset);
 }
 
-void Scheduler::pauseVsyncCallback(const android::sp<android::Scheduler::ConnectionHandle>& handle,
-                                   bool pause) {
-    RETURN_IF_INVALID();
-    mConnections[handle->id]->thread->pauseVsyncCallback(pause);
-}
-
 void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats) {
     stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
     stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
@@ -255,7 +249,6 @@
 
 void Scheduler::setVsyncPeriod(const nsecs_t period) {
     std::lock_guard<std::mutex> lock(mHWVsyncLock);
-    mPrimaryDispSync->reset();
     mPrimaryDispSync->setPeriod(period);
 
     if (!mPrimaryHWVsyncEnabled) {
@@ -265,12 +258,13 @@
     }
 }
 
-void Scheduler::addResyncSample(const nsecs_t timestamp) {
+void Scheduler::addResyncSample(const nsecs_t timestamp, bool* periodChanged) {
     bool needsHwVsync = false;
+    *periodChanged = false;
     { // Scope for the lock
         std::lock_guard<std::mutex> lock(mHWVsyncLock);
         if (mPrimaryHWVsyncEnabled) {
-            needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
+            needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp, periodChanged);
         }
     }
 
diff --git a/services/surfaceflinger/Scheduler/Scheduler.h b/services/surfaceflinger/Scheduler/Scheduler.h
index 1318fbb..134dc0b 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.h
+++ b/services/surfaceflinger/Scheduler/Scheduler.h
@@ -131,9 +131,6 @@
     // Offers ability to modify phase offset in the event thread.
     void setPhaseOffset(const sp<ConnectionHandle>& handle, nsecs_t phaseOffset);
 
-    // pause/resume vsync callback generation to avoid sending vsync callbacks during config switch
-    void pauseVsyncCallback(const sp<ConnectionHandle>& handle, bool pause);
-
     void getDisplayStatInfo(DisplayStatInfo* stats);
 
     void enableHardwareVsync();
@@ -142,7 +139,9 @@
     // Creates a callback for resyncing.
     ResyncCallback makeResyncCallback(GetVsyncPeriod&& getVsyncPeriod);
     void setRefreshSkipCount(int count);
-    void addResyncSample(const nsecs_t timestamp);
+    // Passes a vsync sample to DispSync. periodChange will be true if DipSync
+    // detected that the vsync period changed, and false otherwise.
+    void addResyncSample(const nsecs_t timestamp, bool* periodChanged);
     void addPresentFence(const std::shared_ptr<FenceTime>& fenceTime);
     void setIgnorePresentFences(bool ignore);
     nsecs_t expectedPresentTime();
diff --git a/services/surfaceflinger/Scheduler/SchedulerUtils.h b/services/surfaceflinger/Scheduler/SchedulerUtils.h
index a935cac..3bf3922 100644
--- a/services/surfaceflinger/Scheduler/SchedulerUtils.h
+++ b/services/surfaceflinger/Scheduler/SchedulerUtils.h
@@ -34,6 +34,7 @@
 // the config is not visible to SF, and is completely maintained by HWC. However, we would
 // still like to keep track of time when the device is in this config.
 static constexpr int SCREEN_OFF_CONFIG_ID = -1;
+static constexpr uint32_t HWC2_SCREEN_OFF_CONFIG_ID = 0xffffffff;
 
 // This number is used when we try to determine how long does a given layer stay relevant.
 // Currently it is set to 100ms, because that would indicate 10Hz rendering.
diff --git a/services/surfaceflinger/Scheduler/VSyncModulator.h b/services/surfaceflinger/Scheduler/VSyncModulator.h
index dab2003..1a0de08 100644
--- a/services/surfaceflinger/Scheduler/VSyncModulator.h
+++ b/services/surfaceflinger/Scheduler/VSyncModulator.h
@@ -30,9 +30,10 @@
  */
 class VSyncModulator {
 private:
-    // Number of frames we'll keep the early phase offsets once they are activated. This acts as a
-    // low-pass filter in case the client isn't quick enough in sending new transactions.
-    const int MIN_EARLY_FRAME_COUNT = 2;
+    // Number of frames we'll keep the early phase offsets once they are activated for a
+    // transaction. This acts as a low-pass filter in case the client isn't quick enough in
+    // sending new transactions.
+    const int MIN_EARLY_FRAME_COUNT_TRANSACTION = 2;
 
 public:
     struct Offsets {
@@ -85,7 +86,7 @@
 
     void setTransactionStart(Scheduler::TransactionStart transactionStart) {
         if (transactionStart == Scheduler::TransactionStart::EARLY) {
-            mRemainingEarlyFrameCount = MIN_EARLY_FRAME_COUNT;
+            mRemainingEarlyFrameCount = MIN_EARLY_FRAME_COUNT_TRANSACTION;
         }
 
         // An early transaction stays an early transaction.
@@ -103,6 +104,26 @@
         updateOffsets();
     }
 
+    // Called when we send a refresh rate change to hardware composer, so that
+    // we can move into early offsets.
+    void onRefreshRateChangeInitiated() {
+        if (mRefreshRateChangePending) {
+            return;
+        }
+        mRefreshRateChangePending = true;
+        updateOffsets();
+    }
+
+    // Called when we detect from vsync signals that the refresh rate changed.
+    // This way we can move out of early offsets if no longer necessary.
+    void onRefreshRateChangeDetected() {
+        if (!mRefreshRateChangePending) {
+            return;
+        }
+        mRefreshRateChangePending = false;
+        updateOffsets();
+    }
+
     void onRefreshed(bool usedRenderEngine) {
         bool updateOffsetsNeeded = false;
         if (mRemainingEarlyFrameCount > 0) {
@@ -147,8 +168,10 @@
     }
 
     Offsets getOffsets() {
+        // Early offsets are used if we're in the middle of a refresh rate
+        // change, or if we recently begin a transaction.
         if (mTransactionStart == Scheduler::TransactionStart::EARLY ||
-            mRemainingEarlyFrameCount > 0) {
+            mRemainingEarlyFrameCount > 0 || mRefreshRateChangePending) {
             return mEarlyOffsets;
         } else if (mLastFrameUsedRenderEngine) {
             return mEarlyGlOffsets;
@@ -173,6 +196,7 @@
     std::atomic<Scheduler::TransactionStart> mTransactionStart =
             Scheduler::TransactionStart::NORMAL;
     std::atomic<bool> mLastFrameUsedRenderEngine = false;
+    std::atomic<bool> mRefreshRateChangePending = false;
     std::atomic<int> mRemainingEarlyFrameCount = 0;
 };
 
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index bd3f156..6063555 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -860,7 +860,9 @@
         info.xdpi = xdpi;
         info.ydpi = ydpi;
         info.fps = 1e9 / hwConfig->getVsyncPeriod();
-        info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
+        const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
+        const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
+        info.appVsyncOffset = offset.late.app;
 
         // This is how far in advance a buffer must be queued for
         // presentation at a given time.  If you want a buffer to appear
@@ -874,8 +876,7 @@
         //
         // We add an additional 1ms to allow for processing time and
         // differences between the ideal and actual refresh rate.
-        info.presentationDeadline =
-                hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
+        info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
 
         // All non-virtual displays are currently considered secure.
         info.secure = true;
@@ -922,11 +923,15 @@
     mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
 
     if (!mDesiredActiveConfigChanged) {
-        // This is the first time we set the desired
-        mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
-
         // This will trigger HWC refresh without resetting the idle timer.
         repaintEverythingForHWC();
+        // Start receiving vsync samples now, so that we can detect a period
+        // switch.
+        mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
+        mPhaseOffsets->setRefreshRateType(info.type);
+        const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
+        mVsyncModulator.onRefreshRateChangeInitiated();
+        mVsyncModulator.setPhaseOffsets(early, gl, late);
     }
     mDesiredActiveConfigChanged = true;
     ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
@@ -959,6 +964,7 @@
     display->setActiveConfig(mUpcomingActiveConfig.configId);
 
     mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
+    mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
     const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
     mVsyncModulator.setPhaseOffsets(early, gl, late);
     ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
@@ -1000,8 +1006,6 @@
         // display is not valid or we are already in the requested mode
         // on both cases there is nothing left to do
         std::lock_guard<std::mutex> lock(mActiveConfigLock);
-        mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
-        mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
         mDesiredActiveConfigChanged = false;
         ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
         return false;
@@ -1012,6 +1016,7 @@
     // Make sure the desired config is still allowed
     if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
         std::lock_guard<std::mutex> lock(mActiveConfigLock);
+        mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
         mDesiredActiveConfig.configId = display->getActiveConfig();
         return false;
     }
@@ -1403,7 +1408,11 @@
         return;
     }
 
-    mScheduler->addResyncSample(timestamp);
+    bool periodChanged = false;
+    mScheduler->addResyncSample(timestamp, &periodChanged);
+    if (periodChanged) {
+        mVsyncModulator.onRefreshRateChangeDetected();
+    }
 }
 
 void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
@@ -1436,8 +1445,6 @@
         return;
     }
 
-    mPhaseOffsets->setRefreshRateType(refreshRate);
-
     if (desiredConfigId == display->getActiveConfig()) {
         return;
     }
@@ -3393,20 +3400,12 @@
         const sp<IBinder>& handle,
         const sp<IGraphicBufferProducer>& gbc,
         const sp<Layer>& lbc,
-        const sp<IBinder>& parentHandle,
+        const sp<Layer>& parent,
         bool addToCurrentState)
 {
     // add this layer to the current state list
     {
         Mutex::Autolock _l(mStateLock);
-        sp<Layer> parent;
-        if (parentHandle != nullptr) {
-            parent = fromHandle(parentHandle);
-            if (parent == nullptr) {
-                return NAME_NOT_FOUND;
-            }
-        }
-
         if (mNumLayers >= MAX_LAYERS) {
             ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
                   MAX_LAYERS);
@@ -4015,10 +4014,10 @@
     return flags;
 }
 
-status_t SurfaceFlinger::createLayer(
-        const String8& name, const sp<Client>& client, uint32_t w, uint32_t h, PixelFormat format,
-        uint32_t flags, LayerMetadata metadata, sp<IBinder>* handle,
-        sp<IGraphicBufferProducer>* gbp, const sp<IBinder>& parentHandle) {
+status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
+                                     uint32_t h, PixelFormat format, uint32_t flags,
+                                     LayerMetadata metadata, sp<IBinder>* handle,
+                                     sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
     if (int32_t(w|h) < 0) {
         ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
                 int(w), int(h));
@@ -4083,14 +4082,12 @@
         return result;
     }
 
-    mLayersByLocalBinderToken.emplace((*handle)->localBinder(), layer);
-
     if (primaryDisplayOnly) {
         layer->setPrimaryDisplayOnly();
     }
 
     bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
-    result = addClientLayer(client, *handle, *gbp, layer, parentHandle,
+    result = addClientLayer(client, *handle, *gbp, layer, *parent,
             addToCurrentState);
     if (result != NO_ERROR) {
         return result;
@@ -4208,16 +4205,6 @@
         mCurrentState.layersSortedByZ.remove(layer);
     }
     markLayerPendingRemovalLocked(layer);
-
-    auto it = mLayersByLocalBinderToken.begin();
-    while (it != mLayersByLocalBinderToken.end()) {
-        if (it->second == layer) {
-            it = mLayersByLocalBinderToken.erase(it);
-        } else {
-            it++;
-        }
-    }
-
     layer.clear();
 }
 
@@ -5007,7 +4994,7 @@
     }
     // Numbers from 1000 to 1034 are currently used for backdoors. The code
     // in onTransact verifies that the user is root, and has access to use SF.
-    if (code >= 1000 && code <= 1034) {
+    if (code >= 1000 && code <= 1035) {
         ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
         return OK;
     }
@@ -5330,6 +5317,19 @@
                 }
                 return NO_ERROR;
             }
+            case 1035: {
+                n = data.readInt32();
+                mDebugDisplayConfigSetByBackdoor = false;
+                if (n >= 0) {
+                    const auto displayToken = getInternalDisplayToken();
+                    status_t result = setAllowedDisplayConfigs(displayToken, {n});
+                    if (result != NO_ERROR) {
+                        return result;
+                    }
+                    mDebugDisplayConfigSetByBackdoor = true;
+                }
+                return NO_ERROR;
+            }
         }
     }
     return err;
@@ -5485,50 +5485,34 @@
         const bool mChildrenOnly;
     };
 
-    int reqWidth = 0;
-    int reqHeight = 0;
-    sp<Layer> parent;
+    auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
+    auto parent = layerHandle->owner.promote();
+
+    if (parent == nullptr || parent->isRemovedFromCurrentState()) {
+        ALOGE("captureLayers called with a removed parent");
+        return NAME_NOT_FOUND;
+    }
+
+    const int uid = IPCThreadState::self()->getCallingUid();
+    const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
+    if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
+        ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
+        return PERMISSION_DENIED;
+    }
+
     Rect crop(sourceCrop);
-    std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
+    if (sourceCrop.width() <= 0) {
+        crop.left = 0;
+        crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
+    }
 
-    {
-        Mutex::Autolock _l(mStateLock);
+    if (sourceCrop.height() <= 0) {
+        crop.top = 0;
+        crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
+    }
 
-        parent = fromHandle(layerHandleBinder);
-        if (parent == nullptr || parent->isRemovedFromCurrentState()) {
-            ALOGE("captureLayers called with an invalid or removed parent");
-            return NAME_NOT_FOUND;
-        }
-
-        const int uid = IPCThreadState::self()->getCallingUid();
-        const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
-        if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
-            ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
-            return PERMISSION_DENIED;
-        }
-
-        if (sourceCrop.width() <= 0) {
-            crop.left = 0;
-            crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
-        }
-
-        if (sourceCrop.height() <= 0) {
-            crop.top = 0;
-            crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
-        }
-        reqWidth = crop.width() * frameScale;
-        reqHeight = crop.height() * frameScale;
-
-        for (const auto& handle : excludeHandles) {
-            sp<Layer> excludeLayer = fromHandle(handle);
-            if (excludeLayer != nullptr) {
-                excludeLayers.emplace(excludeLayer);
-            } else {
-                ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
-                return NAME_NOT_FOUND;
-            }
-        }
-    } // mStateLock
+    int32_t reqWidth = crop.width() * frameScale;
+    int32_t reqHeight = crop.height() * frameScale;
 
     // really small crop or frameScale
     if (reqWidth <= 0) {
@@ -5538,6 +5522,18 @@
         reqHeight = 1;
     }
 
+    std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
+    for (const auto& handle : excludeHandles) {
+        BBinder* local = handle->localBinder();
+        if (local != nullptr) {
+            auto layerHandle = reinterpret_cast<Layer::Handle*>(local);
+            excludeLayers.emplace(layerHandle->owner.promote());
+        } else {
+            ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
+            return NAME_NOT_FOUND;
+        }
+    }
+
     LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
     auto traverseLayers = [parent, childrenOnly,
                            &excludeLayers](const LayerVector::Visitor& visitor) {
@@ -5846,6 +5842,11 @@
         return BAD_VALUE;
     }
 
+    if (mDebugDisplayConfigSetByBackdoor) {
+        // ignore this request as config is overridden by backdoor
+        return NO_ERROR;
+    }
+
     postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
         const auto display = getDisplayDeviceLocked(displayToken);
         if (!display) {
@@ -5884,18 +5885,6 @@
     mFlinger->setInputWindowsFinished();
 }
 
-sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
-    BBinder *b = handle->localBinder();
-    if (b == nullptr) {
-        return nullptr;
-    }
-    auto it = mLayersByLocalBinderToken.find(b);
-    if (it != mLayersByLocalBinderToken.end()) {
-        return it->second.promote();
-    }
-    return nullptr;
-}
-
 } // namespace android
 
 #if defined(__gl_h_)
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index d8108c5..7a7ad33 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -313,8 +313,6 @@
         return mTransactionCompletedThread;
     }
 
-    sp<Layer> fromHandle(const sp<IBinder>& handle) REQUIRES(mStateLock);
-
 private:
     friend class BufferLayer;
     friend class BufferQueueLayer;
@@ -575,10 +573,9 @@
     /* ------------------------------------------------------------------------
      * Layer management
      */
-    status_t createLayer(
-            const String8& name, const sp<Client>& client, uint32_t w, uint32_t h,
-            PixelFormat format, uint32_t flags, LayerMetadata metadata,
-            sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, const sp<IBinder>& parentHandle);
+    status_t createLayer(const String8& name, const sp<Client>& client, uint32_t w, uint32_t h,
+                         PixelFormat format, uint32_t flags, LayerMetadata metadata,
+                         sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent);
 
     status_t createBufferQueueLayer(const sp<Client>& client, const String8& name, uint32_t w,
                                     uint32_t h, uint32_t flags, LayerMetadata metadata,
@@ -610,7 +607,7 @@
             const sp<IBinder>& handle,
             const sp<IGraphicBufferProducer>& gbc,
             const sp<Layer>& lbc,
-            const sp<IBinder>& parentHandle,
+            const sp<Layer>& parent,
             bool addToCurrentState);
 
     // Traverse through all the layers and compute and cache its bounds.
@@ -984,9 +981,6 @@
     std::map<wp<IBinder>, sp<DisplayDevice>> mDisplays;
     std::unordered_map<DisplayId, sp<IBinder>> mPhysicalDisplayTokens;
 
-    // protected by mStateLock
-    std::unordered_map<BBinder*, wp<Layer>> mLayersByLocalBinderToken;
-
     // don't use a lock for these, we don't care
     int mDebugRegion = 0;
     bool mDebugDisableHWC = false;
@@ -1148,6 +1142,9 @@
     Hwc2::impl::PowerAdvisor mPowerAdvisor;
 
     std::unique_ptr<RefreshRateOverlay> mRefreshRateOverlay;
+
+    // Flag used to set override allowed display configs from backdoor
+    bool mDebugDisplayConfigSetByBackdoor = false;
 };
 
 } // namespace android
diff --git a/services/surfaceflinger/TransactionCompletedThread.cpp b/services/surfaceflinger/TransactionCompletedThread.cpp
index 6b2b583..34df606 100644
--- a/services/surfaceflinger/TransactionCompletedThread.cpp
+++ b/services/surfaceflinger/TransactionCompletedThread.cpp
@@ -144,6 +144,9 @@
         } else {
             ALOGW("cannot find listener in mPendingTransactions");
         }
+        if (listener->second.size() == 0) {
+            mPendingTransactions.erase(listener);
+        }
 
         status_t err = addCallbackHandle(handle);
         if (err != NO_ERROR) {
@@ -231,7 +234,9 @@
 
                 // If we are still waiting on the callback handles for this transaction, stop
                 // here because all transaction callbacks for the same listener must come in order
-                if (mPendingTransactions[listener].count(transactionStats.callbackIds) != 0) {
+                auto pendingTransactions = mPendingTransactions.find(listener);
+                if (pendingTransactions != mPendingTransactions.end() &&
+                    pendingTransactions->second.count(transactionStats.callbackIds) != 0) {
                     break;
                 }
 
diff --git a/services/surfaceflinger/sysprop/SurfaceFlingerProperties.sysprop b/services/surfaceflinger/sysprop/SurfaceFlingerProperties.sysprop
index 830c03e..d369096 100644
--- a/services/surfaceflinger/sysprop/SurfaceFlingerProperties.sysprop
+++ b/services/surfaceflinger/sysprop/SurfaceFlingerProperties.sysprop
@@ -36,7 +36,7 @@
 prop {
     api_name: "vsync_event_phase_offset_ns"
     type: Long
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.vsync_event_phase_offset_ns"
 }
@@ -44,7 +44,7 @@
 prop {
     api_name: "vsync_sf_event_phase_offset_ns"
     type: Long
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.vsync_sf_event_phase_offset_ns"
 }
@@ -53,7 +53,7 @@
 prop {
     api_name: "use_context_priority"
     type: Boolean
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.use_context_priority"
 }
@@ -62,7 +62,7 @@
 prop {
     api_name: "max_frame_buffer_acquired_buffers"
     type: Long
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.max_frame_buffer_acquired_buffers"
 }
@@ -80,7 +80,7 @@
 prop {
     api_name: "has_wide_color_display"
     type: Boolean
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.has_wide_color_display"
 }
@@ -90,7 +90,7 @@
 prop {
     api_name: "running_without_sync_framework"
     type: Boolean
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.running_without_sync_framework"
 }
@@ -108,7 +108,7 @@
 prop {
     api_name: "has_HDR_display"
     type: Boolean
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.has_HDR_display"
 }
@@ -117,7 +117,7 @@
 prop {
     api_name: "present_time_offset_from_vsync_ns"
     type: Long
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.present_time_offset_from_vsync_ns"
 }
@@ -129,7 +129,7 @@
 prop {
     api_name: "force_hwc_copy_for_virtual_displays"
     type: Boolean
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.force_hwc_copy_for_virtual_displays"
 }
@@ -139,7 +139,7 @@
 prop {
     api_name: "max_virtual_display_dimension"
     type: Long
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.max_virtual_display_dimension"
 }
@@ -151,7 +151,7 @@
 prop {
     api_name: "use_vr_flinger"
     type: Boolean
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.use_vr_flinger"
 }
@@ -161,7 +161,7 @@
 prop {
     api_name: "start_graphics_allocator_service"
     type: Boolean
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.start_graphics_allocator_service"
 }
@@ -171,7 +171,7 @@
     api_name: "primary_display_orientation"
     type: Enum
     enum_values: "ORIENTATION_0|ORIENTATION_90|ORIENTATION_180|ORIENTATION_270"
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.primary_display_orientation"
 }
@@ -182,7 +182,7 @@
 prop {
     api_name: "use_color_management"
     type: Boolean
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.use_color_management"
 }
@@ -209,7 +209,7 @@
 prop {
     api_name: "default_composition_dataspace"
     type: Long
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.default_composition_dataspace"
 }
@@ -220,7 +220,7 @@
 prop {
     api_name: "default_composition_pixel_format"
     type: Integer
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.default_composition_pixel_format"
 }
@@ -235,7 +235,7 @@
 prop {
     api_name: "wcg_composition_dataspace"
     type: Long
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.wcg_composition_dataspace"
 }
@@ -246,7 +246,7 @@
 prop {
     api_name: "wcg_composition_pixel_format"
     type: Integer
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.wcg_composition_pixel_format"
 }
@@ -258,7 +258,7 @@
 prop {
     api_name: "display_primary_red"
     type: DoubleList
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.display_primary_red"
 }
@@ -266,7 +266,7 @@
 prop {
     api_name: "display_primary_green"
     type: DoubleList
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.display_primary_green"
 }
@@ -274,7 +274,7 @@
 prop {
     api_name: "display_primary_blue"
     type: DoubleList
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.display_primary_blue"
 }
@@ -282,7 +282,7 @@
 prop {
     api_name: "display_primary_white"
     type: DoubleList
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.display_primary_white"
 }
@@ -293,7 +293,7 @@
 prop {
     api_name: "set_idle_timer_ms"
     type: Integer
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.set_idle_timer_ms"
 }
@@ -303,7 +303,7 @@
 prop {
     api_name: "use_smart_90_for_video"
     type: Boolean
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.use_smart_90_for_video"
 }
@@ -311,7 +311,7 @@
 prop {
     api_name: "enable_protected_contents"
     type: Boolean
-    scope: Internal
+    scope: System
     access: Readonly
     prop_name: "ro.surface_flinger.protected_contents"
 }
diff --git a/services/surfaceflinger/sysprop/api/system-current.txt b/services/surfaceflinger/sysprop/api/system-current.txt
index d802177..3c39b51 100644
--- a/services/surfaceflinger/sysprop/api/system-current.txt
+++ b/services/surfaceflinger/sysprop/api/system-current.txt
@@ -1 +1,41 @@
 // Signature format: 2.0
+package android.sysprop {
+
+  public final class SurfaceFlingerProperties {
+    method public static java.util.Optional<java.lang.Long> default_composition_dataspace();
+    method public static java.util.Optional<java.lang.Integer> default_composition_pixel_format();
+    method public static java.util.List<java.lang.Double> display_primary_blue();
+    method public static java.util.List<java.lang.Double> display_primary_green();
+    method public static java.util.List<java.lang.Double> display_primary_red();
+    method public static java.util.List<java.lang.Double> display_primary_white();
+    method public static java.util.Optional<java.lang.Boolean> enable_protected_contents();
+    method public static java.util.Optional<java.lang.Boolean> force_hwc_copy_for_virtual_displays();
+    method public static java.util.Optional<java.lang.Boolean> has_HDR_display();
+    method public static java.util.Optional<java.lang.Boolean> has_wide_color_display();
+    method public static java.util.Optional<java.lang.Long> max_frame_buffer_acquired_buffers();
+    method public static java.util.Optional<java.lang.Long> max_virtual_display_dimension();
+    method public static java.util.Optional<java.lang.Long> present_time_offset_from_vsync_ns();
+    method public static java.util.Optional<android.sysprop.SurfaceFlingerProperties.primary_display_orientation_values> primary_display_orientation();
+    method public static java.util.Optional<java.lang.Boolean> running_without_sync_framework();
+    method public static java.util.Optional<java.lang.Integer> set_idle_timer_ms();
+    method public static java.util.Optional<java.lang.Boolean> start_graphics_allocator_service();
+    method public static java.util.Optional<java.lang.Boolean> use_color_management();
+    method public static java.util.Optional<java.lang.Boolean> use_context_priority();
+    method public static java.util.Optional<java.lang.Boolean> use_smart_90_for_video();
+    method public static java.util.Optional<java.lang.Boolean> use_vr_flinger();
+    method public static java.util.Optional<java.lang.Long> vsync_event_phase_offset_ns();
+    method public static java.util.Optional<java.lang.Long> vsync_sf_event_phase_offset_ns();
+    method public static java.util.Optional<java.lang.Long> wcg_composition_dataspace();
+    method public static java.util.Optional<java.lang.Integer> wcg_composition_pixel_format();
+  }
+
+  public enum SurfaceFlingerProperties.primary_display_orientation_values {
+    method public String getPropValue();
+    enum_constant public static final android.sysprop.SurfaceFlingerProperties.primary_display_orientation_values ORIENTATION_0;
+    enum_constant public static final android.sysprop.SurfaceFlingerProperties.primary_display_orientation_values ORIENTATION_180;
+    enum_constant public static final android.sysprop.SurfaceFlingerProperties.primary_display_orientation_values ORIENTATION_270;
+    enum_constant public static final android.sysprop.SurfaceFlingerProperties.primary_display_orientation_values ORIENTATION_90;
+  }
+
+}
+
diff --git a/services/surfaceflinger/tests/Android.bp b/services/surfaceflinger/tests/Android.bp
index d3c87bf..003ae7f 100644
--- a/services/surfaceflinger/tests/Android.bp
+++ b/services/surfaceflinger/tests/Android.bp
@@ -19,10 +19,10 @@
     srcs: [
         "BufferGenerator.cpp",
         "Credentials_test.cpp",
-        "InvalidHandles_test.cpp",
         "Stress_test.cpp",
         "SurfaceInterceptor_test.cpp",
         "Transaction_test.cpp",
+        "VirtualDisplay_test.cpp",
     ],
     data: ["SurfaceFlinger_test.filter"],
     static_libs: [
diff --git a/services/surfaceflinger/tests/InvalidHandles_test.cpp b/services/surfaceflinger/tests/InvalidHandles_test.cpp
deleted file mode 100644
index 42d1f5a..0000000
--- a/services/surfaceflinger/tests/InvalidHandles_test.cpp
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <binder/Binder.h>
-
-#include <gtest/gtest.h>
-
-#include <gui/ISurfaceComposer.h>
-#include <gui/SurfaceComposerClient.h>
-#include <private/gui/ComposerService.h>
-#include <ui/Rect.h>
-
-namespace android {
-namespace {
-
-class NotALayer : public BBinder {};
-
-/**
- * For all of these tests we make a SurfaceControl with an invalid layer handle
- * and verify we aren't able to trick SurfaceFlinger.
- */
-class InvalidHandleTest : public ::testing::Test {
-protected:
-    sp<SurfaceComposerClient> mScc;
-    sp<SurfaceControl> mNotSc;
-    void SetUp() override {
-        mScc = new SurfaceComposerClient;
-        ASSERT_EQ(NO_ERROR, mScc->initCheck());
-        mNotSc = makeNotSurfaceControl();
-    }
-
-    sp<SurfaceControl> makeNotSurfaceControl() {
-        return new SurfaceControl(mScc, new NotALayer(), nullptr, true);
-    }
-};
-
-TEST_F(InvalidHandleTest, createSurfaceInvalidHandle) {
-    auto notSc = makeNotSurfaceControl();
-    ASSERT_EQ(nullptr,
-              mScc->createSurface(String8("lolcats"), 19, 47, PIXEL_FORMAT_RGBA_8888, 0,
-                                  notSc.get())
-                      .get());
-}
-
-TEST_F(InvalidHandleTest, captureLayersInvalidHandle) {
-    sp<ISurfaceComposer> sf(ComposerService::getComposerService());
-    sp<GraphicBuffer> outBuffer;
-
-    ASSERT_EQ(NAME_NOT_FOUND,
-              sf->captureLayers(mNotSc->getHandle(), &outBuffer, Rect::EMPTY_RECT, 1.0f));
-}
-
-} // namespace
-} // namespace android
diff --git a/services/surfaceflinger/tests/SurfaceFlinger_test.filter b/services/surfaceflinger/tests/SurfaceFlinger_test.filter
index a8d09ea..5ebae1e 100644
--- a/services/surfaceflinger/tests/SurfaceFlinger_test.filter
+++ b/services/surfaceflinger/tests/SurfaceFlinger_test.filter
@@ -1,5 +1,5 @@
 {
         "presubmit": {
-            "filter": "CredentialsTest.*:SurfaceFlingerStress.*:SurfaceInterceptorTest.*:LayerTransactionTest.*:LayerTypeTransactionTest.*:LayerUpdateTest.*:GeometryLatchingTest.*:CropLatchingTest.*:ChildLayerTest.*:ScreenCaptureTest.*:ScreenCaptureChildOnlyTest.*:DereferenceSurfaceControlTest.*:BoundlessLayerTest.*:MultiDisplayLayerBoundsTest.*:InvalidHandleTest.*"
+            "filter": "CredentialsTest.*:SurfaceFlingerStress.*:SurfaceInterceptorTest.*:LayerTransactionTest.*:LayerTypeTransactionTest.*:LayerUpdateTest.*:GeometryLatchingTest.*:CropLatchingTest.*:ChildLayerTest.*:ScreenCaptureTest.*:ScreenCaptureChildOnlyTest.*:DereferenceSurfaceControlTest.*:BoundlessLayerTest.*:MultiDisplayLayerBoundsTest.*:InvalidHandleTest.*:VirtualDisplayTest.*"
         }
 }
diff --git a/services/surfaceflinger/tests/VirtualDisplay_test.cpp b/services/surfaceflinger/tests/VirtualDisplay_test.cpp
new file mode 100644
index 0000000..9fd2227
--- /dev/null
+++ b/services/surfaceflinger/tests/VirtualDisplay_test.cpp
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <binder/Binder.h>
+
+#include <gtest/gtest.h>
+#include <gui/GLConsumer.h>
+#include <gui/Surface.h>
+#include <gui/SurfaceComposerClient.h>
+
+namespace android {
+namespace {
+
+class VirtualDisplayTest : public ::testing::Test {
+protected:
+    void SetUp() override {
+        sp<IGraphicBufferConsumer> consumer;
+
+        BufferQueue::createBufferQueue(&mProducer, &consumer);
+        consumer->setConsumerName(String8("Virtual disp consumer"));
+        consumer->setDefaultBufferSize(100, 100);
+
+        mGLConsumer = new GLConsumer(consumer, GLConsumer::TEXTURE_EXTERNAL, true, false);
+    }
+
+    sp<IGraphicBufferProducer> mProducer;
+    sp<GLConsumer> mGLConsumer;
+};
+
+TEST_F(VirtualDisplayTest, VirtualDisplayDestroyedSurfaceReuse) {
+    sp<IBinder> virtualDisplay =
+            SurfaceComposerClient::createDisplay(String8("VirtualDisplay"), false /*secure*/);
+
+    SurfaceComposerClient::Transaction t;
+    t.setDisplaySurface(virtualDisplay, mProducer);
+    t.apply(true);
+
+    SurfaceComposerClient::destroyDisplay(virtualDisplay);
+    virtualDisplay.clear();
+    // Sync here to ensure the display was completely destroyed in SF
+    t.apply(true);
+
+    sp<Surface> surface = new Surface(mProducer);
+    sp<ANativeWindow> window(surface);
+
+    ASSERT_EQ(NO_ERROR, native_window_api_connect(window.get(), NATIVE_WINDOW_API_EGL));
+}
+
+} // namespace
+} // namespace android
\ No newline at end of file
diff --git a/services/surfaceflinger/tests/unittests/DispSyncSourceTest.cpp b/services/surfaceflinger/tests/unittests/DispSyncSourceTest.cpp
index 92bdebd..2e705da 100644
--- a/services/surfaceflinger/tests/unittests/DispSyncSourceTest.cpp
+++ b/services/surfaceflinger/tests/unittests/DispSyncSourceTest.cpp
@@ -142,23 +142,5 @@
     }
 }
 
-TEST_F(DispSyncSourceTest, pauseCallbacks) {
-    createDispSyncSource();
-    EXPECT_TRUE(mDispSyncSource);
-
-    mDispSyncSource->setVSyncEnabled(true);
-    EXPECT_EQ(mDispSync->getCallbackPhase(), mPhaseOffset.count());
-    mDispSync->triggerCallback();
-    EXPECT_TRUE(mVSyncEventCallRecorder.waitForCall().has_value());
-
-    mDispSyncSource->pauseVsyncCallback(true);
-    mDispSync->triggerCallback();
-    EXPECT_FALSE(mVSyncEventCallRecorder.waitForUnexpectedCall().has_value());
-
-    mDispSyncSource->pauseVsyncCallback(false);
-    mDispSync->triggerCallback();
-    EXPECT_TRUE(mVSyncEventCallRecorder.waitForUnexpectedCall().has_value());
-}
-
 } // namespace
 } // namespace android
diff --git a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
index d83f1bd..97f9e6a 100644
--- a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
+++ b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
@@ -358,6 +358,9 @@
                 .WillRepeatedly(Return(0));
         EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_SET_USAGE64))
                 .WillRepeatedly(Return(0));
+        EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_API_DISCONNECT))
+                .WillRepeatedly(Return(0));
+
         return injector;
     }
 
@@ -376,6 +379,8 @@
                 .WillRepeatedly(Return(0));
         EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_SET_USAGE64))
                 .WillRepeatedly(Return(0));
+        EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_API_DISCONNECT))
+                .WillRepeatedly(Return(0));
     }
 
     static void setupFramebufferConsumerBufferQueueCallExpectations(DisplayTransactionTest* test) {
@@ -1198,6 +1203,7 @@
         EXPECT_CALL(*mNativeWindow, perform(NATIVE_WINDOW_SET_BUFFERS_FORMAT)).Times(1);
         EXPECT_CALL(*mNativeWindow, perform(NATIVE_WINDOW_API_CONNECT)).Times(1);
         EXPECT_CALL(*mNativeWindow, perform(NATIVE_WINDOW_SET_USAGE64)).Times(1);
+        EXPECT_CALL(*mNativeWindow, perform(NATIVE_WINDOW_API_DISCONNECT)).Times(1);
         auto displayDevice = mInjector.inject();
 
         displayDevice->getCompositionDisplay()
@@ -2141,6 +2147,7 @@
     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_SET_BUFFERS_FORMAT)).Times(1);
     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_API_CONNECT)).Times(1);
     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_SET_USAGE64)).Times(1);
+    EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_API_DISCONNECT)).Times(1);
     display.inject();
 
     // There is a change to the viewport state
@@ -2185,6 +2192,7 @@
     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_SET_BUFFERS_FORMAT)).Times(1);
     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_API_CONNECT)).Times(1);
     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_SET_USAGE64)).Times(1);
+    EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_API_DISCONNECT)).Times(1);
     display.inject();
 
     // There is a change to the viewport state
@@ -2830,7 +2838,6 @@
 
 struct DispSyncIsSupportedVariant {
     static void setupBeginResyncCallExpectations(DisplayTransactionTest* test) {
-        EXPECT_CALL(*test->mPrimaryDispSync, reset()).Times(1);
         EXPECT_CALL(*test->mPrimaryDispSync, setPeriod(DEFAULT_REFRESH_RATE)).Times(1);
         EXPECT_CALL(*test->mPrimaryDispSync, beginResync()).Times(1);
     }
diff --git a/services/surfaceflinger/tests/unittests/EventThreadTest.cpp b/services/surfaceflinger/tests/unittests/EventThreadTest.cpp
index 249c78f..83a92c8 100644
--- a/services/surfaceflinger/tests/unittests/EventThreadTest.cpp
+++ b/services/surfaceflinger/tests/unittests/EventThreadTest.cpp
@@ -73,7 +73,6 @@
 
     void expectVSyncSetEnabledCallReceived(bool expectedState);
     void expectVSyncSetPhaseOffsetCallReceived(nsecs_t expectedPhaseOffset);
-    void expectVSyncPauseVsyncCallbackCallReceived(bool expectedPause);
     VSyncSource::Callback* expectVSyncSetCallbackCallReceived();
     void expectInterceptCallReceived(nsecs_t expectedTimestamp);
     void expectVsyncEventReceivedByConnection(const char* name,
@@ -88,7 +87,6 @@
     AsyncCallRecorder<void (*)(bool)> mVSyncSetEnabledCallRecorder;
     AsyncCallRecorder<void (*)(VSyncSource::Callback*)> mVSyncSetCallbackCallRecorder;
     AsyncCallRecorder<void (*)(nsecs_t)> mVSyncSetPhaseOffsetCallRecorder;
-    AsyncCallRecorder<void (*)(bool)> mVSyncPauseVsyncCallbackCallRecorder;
     AsyncCallRecorder<void (*)()> mResyncCallRecorder;
     AsyncCallRecorder<void (*)()> mResetIdleTimerCallRecorder;
     AsyncCallRecorder<void (*)(nsecs_t)> mInterceptVSyncCallRecorder;
@@ -114,9 +112,6 @@
     EXPECT_CALL(mVSyncSource, setPhaseOffset(_))
             .WillRepeatedly(Invoke(mVSyncSetPhaseOffsetCallRecorder.getInvocable()));
 
-    EXPECT_CALL(mVSyncSource, pauseVsyncCallback(_))
-            .WillRepeatedly(Invoke(mVSyncPauseVsyncCallbackCallRecorder.getInvocable()));
-
     createThread();
     mConnection = createConnection(mConnectionEventCallRecorder);
 
@@ -166,12 +161,6 @@
     EXPECT_EQ(expectedPhaseOffset, std::get<0>(args.value()));
 }
 
-void EventThreadTest::expectVSyncPauseVsyncCallbackCallReceived(bool expectedPause) {
-    auto args = mVSyncPauseVsyncCallbackCallRecorder.waitForCall();
-    ASSERT_TRUE(args.has_value());
-    EXPECT_EQ(expectedPause, std::get<0>(args.value()));
-}
-
 VSyncSource::Callback* EventThreadTest::expectVSyncSetCallbackCallReceived() {
     auto callbackSet = mVSyncSetCallbackCallRecorder.waitForCall();
     return callbackSet.has_value() ? std::get<0>(callbackSet.value()) : nullptr;
@@ -431,16 +420,6 @@
     expectVSyncSetPhaseOffsetCallReceived(321);
 }
 
-TEST_F(EventThreadTest, pauseVsyncCallbackForwardsToVSyncSource) {
-    mThread->pauseVsyncCallback(true);
-    expectVSyncPauseVsyncCallbackCallReceived(true);
-}
-
-TEST_F(EventThreadTest, resumeVsyncCallbackForwardsToVSyncSource) {
-    mThread->pauseVsyncCallback(false);
-    expectVSyncPauseVsyncCallbackCallReceived(false);
-}
-
 TEST_F(EventThreadTest, postHotplugInternalDisconnect) {
     mThread->onHotplugReceived(INTERNAL_DISPLAY_ID, false);
     expectHotplugEventReceivedByConnection(INTERNAL_DISPLAY_ID, false);
diff --git a/services/surfaceflinger/tests/unittests/FakePhaseOffsets.h b/services/surfaceflinger/tests/unittests/FakePhaseOffsets.h
index 0739f15..cfa8337 100644
--- a/services/surfaceflinger/tests/unittests/FakePhaseOffsets.h
+++ b/services/surfaceflinger/tests/unittests/FakePhaseOffsets.h
@@ -33,6 +33,11 @@
     nsecs_t getCurrentAppOffset() override { return FAKE_PHASE_OFFSET_NS; }
     nsecs_t getCurrentSfOffset() override { return FAKE_PHASE_OFFSET_NS; }
 
+    PhaseOffsets::Offsets getOffsetsForRefreshRate(
+            RefreshRateConfigs::RefreshRateType /*refreshRateType*/) const override {
+        return getCurrentOffsets();
+    }
+
     // Returns early, early GL, and late offsets for Apps and SF.
     PhaseOffsets::Offsets getCurrentOffsets() const override {
         return Offsets{{FAKE_PHASE_OFFSET_NS, FAKE_PHASE_OFFSET_NS},
diff --git a/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp b/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
index 8b37c22..5067fe8 100644
--- a/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
+++ b/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
@@ -37,7 +37,9 @@
 class RefreshRateConfigsTest : public testing::Test {
 protected:
     static constexpr int CONFIG_ID_60 = 0;
+    static constexpr hwc2_config_t HWC2_CONFIG_ID_60 = 0;
     static constexpr int CONFIG_ID_90 = 1;
+    static constexpr hwc2_config_t HWC2_CONFIG_ID_90 = 1;
     static constexpr int64_t VSYNC_60 = 16666667;
     static constexpr int64_t VSYNC_90 = 11111111;
 
@@ -81,7 +83,8 @@
     ASSERT_EQ(rates.end(), rates.find(RefreshRateType::PERFORMANCE));
     ASSERT_EQ(rates.end(), rates.find(RefreshRateType::DEFAULT));
 
-    RefreshRate expectedConfig = RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0};
+    RefreshRate expectedConfig =
+            RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0, HWC2_SCREEN_OFF_CONFIG_ID};
     assertRatesEqual(expectedConfig, *powerSavingRate->second);
 
     ASSERT_TRUE(mConfigs.getRefreshRate(RefreshRateType::POWER_SAVING));
@@ -109,9 +112,10 @@
     ASSERT_NE(rates.end(), defaultRate);
     ASSERT_EQ(rates.end(), rates.find(RefreshRateType::PERFORMANCE));
 
-    RefreshRate expectedPowerSavingConfig = RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0};
+    RefreshRate expectedPowerSavingConfig =
+            RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0, HWC2_SCREEN_OFF_CONFIG_ID};
     assertRatesEqual(expectedPowerSavingConfig, *powerSavingRate->second);
-    RefreshRate expectedDefaultConfig = RefreshRate{CONFIG_ID_60, "60fps", 60};
+    RefreshRate expectedDefaultConfig = RefreshRate{CONFIG_ID_60, "60fps", 60, HWC2_CONFIG_ID_60};
     assertRatesEqual(expectedDefaultConfig, *defaultRate->second);
 
     ASSERT_TRUE(mConfigs.getRefreshRate(RefreshRateType::POWER_SAVING));
@@ -145,11 +149,13 @@
     ASSERT_NE(rates.end(), defaultRate);
     ASSERT_NE(rates.end(), performanceRate);
 
-    RefreshRate expectedPowerSavingConfig = RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0};
+    RefreshRate expectedPowerSavingConfig =
+            RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0, HWC2_SCREEN_OFF_CONFIG_ID};
     assertRatesEqual(expectedPowerSavingConfig, *powerSavingRate->second);
-    RefreshRate expectedDefaultConfig = RefreshRate{CONFIG_ID_60, "60fps", 60};
+    RefreshRate expectedDefaultConfig = RefreshRate{CONFIG_ID_60, "60fps", 60, HWC2_CONFIG_ID_60};
     assertRatesEqual(expectedDefaultConfig, *defaultRate->second);
-    RefreshRate expectedPerformanceConfig = RefreshRate{CONFIG_ID_90, "90fps", 90};
+    RefreshRate expectedPerformanceConfig =
+            RefreshRate{CONFIG_ID_90, "90fps", 90, HWC2_CONFIG_ID_90};
     assertRatesEqual(expectedPerformanceConfig, *performanceRate->second);
 
     ASSERT_TRUE(mConfigs.getRefreshRate(RefreshRateType::POWER_SAVING));
diff --git a/services/surfaceflinger/tests/unittests/mock/MockDispSync.h b/services/surfaceflinger/tests/unittests/mock/MockDispSync.h
index afcda5b..12a349d 100644
--- a/services/surfaceflinger/tests/unittests/mock/MockDispSync.h
+++ b/services/surfaceflinger/tests/unittests/mock/MockDispSync.h
@@ -31,7 +31,7 @@
     MOCK_METHOD0(reset, void());
     MOCK_METHOD1(addPresentFence, bool(const std::shared_ptr<FenceTime>&));
     MOCK_METHOD0(beginResync, void());
-    MOCK_METHOD1(addResyncSample, bool(nsecs_t));
+    MOCK_METHOD2(addResyncSample, bool(nsecs_t, bool*));
     MOCK_METHOD0(endResync, void());
     MOCK_METHOD1(setPeriod, void(nsecs_t));
     MOCK_METHOD0(getPeriod, nsecs_t());
diff --git a/vulkan/libvulkan/code-generator.tmpl b/vulkan/libvulkan/code-generator.tmpl
index f04eb03..bdd3573 100644
--- a/vulkan/libvulkan/code-generator.tmpl
+++ b/vulkan/libvulkan/code-generator.tmpl
@@ -703,6 +703,7 @@
 {{Macro "driver.InterceptedExtensions"}}
 VK_KHR_get_physical_device_properties2
 VK_ANDROID_external_memory_android_hardware_buffer
+VK_KHR_bind_memory2
 {{end}}
 
 
@@ -750,6 +751,9 @@
     {{else if eq $.Name "vkGetInstanceProcAddr"}}true
     {{else if eq $.Name "vkGetDeviceProcAddr"}}true
 
+    {{/* VK_KHR_swapchain v69 requirement */}}
+    {{else if eq $.Name "vkBindImageMemory2"}}true
+    {{else if eq $.Name "vkBindImageMemory2KHR"}}true
     {{end}}
 
     {{$ext := GetAnnotation $ "extension"}}
@@ -985,6 +989,10 @@
     {{else if eq $.Name "vkGetPhysicalDeviceProperties"}}true
     {{else if eq $.Name "vkGetPhysicalDeviceProperties2"}}true
     {{else if eq $.Name "vkGetPhysicalDeviceProperties2KHR"}}true
+
+    {{/* VK_KHR_swapchain v69 requirement */}}
+    {{else if eq $.Name "vkBindImageMemory2"}}true
+    {{else if eq $.Name "vkBindImageMemory2KHR"}}true
     {{end}}
 
     {{$ext := GetAnnotation $ "extension"}}
diff --git a/vulkan/libvulkan/driver.cpp b/vulkan/libvulkan/driver.cpp
index b3259de..491d4d1 100644
--- a/vulkan/libvulkan/driver.cpp
+++ b/vulkan/libvulkan/driver.cpp
@@ -537,6 +537,7 @@
                 // Extensions we don't need to do anything about at this level
                 break;
 
+            case ProcHook::KHR_bind_memory2:
             case ProcHook::KHR_incremental_present:
             case ProcHook::KHR_shared_presentable_image:
             case ProcHook::KHR_swapchain:
@@ -577,6 +578,7 @@
                 // return now as these extensions do not require HAL support
                 return;
             case ProcHook::EXT_hdr_metadata:
+            case ProcHook::KHR_bind_memory2:
                 hook_extensions_.set(ext_bit);
                 break;
             case ProcHook::ANDROID_external_memory_android_hardware_buffer:
diff --git a/vulkan/libvulkan/driver_gen.cpp b/vulkan/libvulkan/driver_gen.cpp
index ec98b9f..574c327 100644
--- a/vulkan/libvulkan/driver_gen.cpp
+++ b/vulkan/libvulkan/driver_gen.cpp
@@ -137,6 +137,15 @@
     }
 }
 
+VKAPI_ATTR VkResult checkedBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfoKHR* pBindInfos) {
+    if (GetData(device).hook_extensions[ProcHook::KHR_bind_memory2]) {
+        return BindImageMemory2KHR(device, bindInfoCount, pBindInfos);
+    } else {
+        Logger(device).Err(device, "VK_KHR_bind_memory2 not enabled. vkBindImageMemory2KHR not executed.");
+        return VK_SUCCESS;
+    }
+}
+
 // clang-format on
 
 const ProcHook g_proc_hooks[] = {
@@ -170,6 +179,20 @@
         nullptr,
     },
     {
+        "vkBindImageMemory2",
+        ProcHook::DEVICE,
+        ProcHook::EXTENSION_CORE,
+        reinterpret_cast<PFN_vkVoidFunction>(BindImageMemory2),
+        nullptr,
+    },
+    {
+        "vkBindImageMemory2KHR",
+        ProcHook::DEVICE,
+        ProcHook::KHR_bind_memory2,
+        reinterpret_cast<PFN_vkVoidFunction>(BindImageMemory2KHR),
+        reinterpret_cast<PFN_vkVoidFunction>(checkedBindImageMemory2KHR),
+    },
+    {
         "vkCreateAndroidSurfaceKHR",
         ProcHook::INSTANCE,
         ProcHook::KHR_android_surface,
@@ -458,6 +481,7 @@
     if (strcmp(name, "VK_KHR_get_surface_capabilities2") == 0) return ProcHook::KHR_get_surface_capabilities2;
     if (strcmp(name, "VK_KHR_get_physical_device_properties2") == 0) return ProcHook::KHR_get_physical_device_properties2;
     if (strcmp(name, "VK_ANDROID_external_memory_android_hardware_buffer") == 0) return ProcHook::ANDROID_external_memory_android_hardware_buffer;
+    if (strcmp(name, "VK_KHR_bind_memory2") == 0) return ProcHook::KHR_bind_memory2;
     // clang-format on
     return ProcHook::EXTENSION_UNKNOWN;
 }
@@ -517,11 +541,13 @@
     INIT_PROC(true, dev, CreateImage);
     INIT_PROC(true, dev, DestroyImage);
     INIT_PROC(true, dev, AllocateCommandBuffers);
+    INIT_PROC(false, dev, BindImageMemory2);
     INIT_PROC(false, dev, GetDeviceQueue2);
     INIT_PROC_EXT(ANDROID_native_buffer, false, dev, GetSwapchainGrallocUsageANDROID);
     INIT_PROC_EXT(ANDROID_native_buffer, false, dev, GetSwapchainGrallocUsage2ANDROID);
     INIT_PROC_EXT(ANDROID_native_buffer, true, dev, AcquireImageANDROID);
     INIT_PROC_EXT(ANDROID_native_buffer, true, dev, QueueSignalReleaseImageANDROID);
+    INIT_PROC_EXT(KHR_bind_memory2, true, dev, BindImageMemory2KHR);
     // clang-format on
 
     return success;
diff --git a/vulkan/libvulkan/driver_gen.h b/vulkan/libvulkan/driver_gen.h
index 14c3aba..3faf6c0 100644
--- a/vulkan/libvulkan/driver_gen.h
+++ b/vulkan/libvulkan/driver_gen.h
@@ -46,6 +46,7 @@
         KHR_get_surface_capabilities2,
         KHR_get_physical_device_properties2,
         ANDROID_external_memory_android_hardware_buffer,
+        KHR_bind_memory2,
 
         EXTENSION_CORE,  // valid bit
         EXTENSION_COUNT,
@@ -85,11 +86,13 @@
     PFN_vkCreateImage CreateImage;
     PFN_vkDestroyImage DestroyImage;
     PFN_vkAllocateCommandBuffers AllocateCommandBuffers;
+    PFN_vkBindImageMemory2 BindImageMemory2;
     PFN_vkGetDeviceQueue2 GetDeviceQueue2;
     PFN_vkGetSwapchainGrallocUsageANDROID GetSwapchainGrallocUsageANDROID;
     PFN_vkGetSwapchainGrallocUsage2ANDROID GetSwapchainGrallocUsage2ANDROID;
     PFN_vkAcquireImageANDROID AcquireImageANDROID;
     PFN_vkQueueSignalReleaseImageANDROID QueueSignalReleaseImageANDROID;
+    PFN_vkBindImageMemory2KHR BindImageMemory2KHR;
     // clang-format on
 };
 
diff --git a/vulkan/libvulkan/swapchain.cpp b/vulkan/libvulkan/swapchain.cpp
index 73fc7b2..bc00190 100644
--- a/vulkan/libvulkan/swapchain.cpp
+++ b/vulkan/libvulkan/swapchain.cpp
@@ -16,17 +16,19 @@
 
 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
 
-#include <algorithm>
-
+#include <android/hardware/graphics/common/1.0/types.h>
 #include <grallocusage/GrallocUsageConversion.h>
 #include <log/log.h>
-#include <ui/BufferQueueDefs.h>
 #include <sync/sync.h>
+#include <system/window.h>
+#include <ui/BufferQueueDefs.h>
 #include <utils/StrongPointer.h>
 #include <utils/Trace.h>
 #include <utils/Vector.h>
-#include <system/window.h>
-#include <android/hardware/graphics/common/1.0/types.h>
+
+#include <algorithm>
+#include <unordered_set>
+#include <vector>
 
 #include "driver.h"
 
@@ -1818,5 +1820,106 @@
     return;
 }
 
+static void InterceptBindImageMemory2(
+    uint32_t bind_info_count,
+    const VkBindImageMemoryInfo* bind_infos,
+    std::vector<VkNativeBufferANDROID>* out_native_buffers,
+    std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
+    out_native_buffers->clear();
+    out_bind_infos->clear();
+
+    if (!bind_info_count)
+        return;
+
+    std::unordered_set<uint32_t> intercepted_indexes;
+
+    for (uint32_t idx = 0; idx < bind_info_count; idx++) {
+        auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
+            bind_infos[idx].pNext);
+        while (info &&
+               info->sType !=
+                   VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
+            info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
+                info->pNext);
+        }
+
+        if (!info)
+            continue;
+
+        ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
+                    "swapchain handle must not be NULL");
+        const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
+        ALOG_ASSERT(
+            info->imageIndex < swapchain->num_images,
+            "imageIndex must be less than the number of images in swapchain");
+
+        ANativeWindowBuffer* buffer =
+            swapchain->images[info->imageIndex].buffer.get();
+        VkNativeBufferANDROID native_buffer = {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wold-style-cast"
+            .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
+#pragma clang diagnostic pop
+            .pNext = bind_infos[idx].pNext,
+            .handle = buffer->handle,
+            .stride = buffer->stride,
+            .format = buffer->format,
+            .usage = int(buffer->usage),
+        };
+        // Reserve enough space to avoid letting re-allocation invalidate the
+        // addresses of the elements inside.
+        out_native_buffers->reserve(bind_info_count);
+        out_native_buffers->emplace_back(native_buffer);
+
+        // Reserve the space now since we know how much is needed now.
+        out_bind_infos->reserve(bind_info_count);
+        out_bind_infos->emplace_back(bind_infos[idx]);
+        out_bind_infos->back().pNext = &out_native_buffers->back();
+
+        intercepted_indexes.insert(idx);
+    }
+
+    if (intercepted_indexes.empty())
+        return;
+
+    for (uint32_t idx = 0; idx < bind_info_count; idx++) {
+        if (intercepted_indexes.count(idx))
+            continue;
+        out_bind_infos->emplace_back(bind_infos[idx]);
+    }
+}
+
+VKAPI_ATTR
+VkResult BindImageMemory2(VkDevice device,
+                          uint32_t bindInfoCount,
+                          const VkBindImageMemoryInfo* pBindInfos) {
+    ATRACE_CALL();
+
+    // out_native_buffers is for maintaining the lifecycle of the constructed
+    // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
+    std::vector<VkNativeBufferANDROID> out_native_buffers;
+    std::vector<VkBindImageMemoryInfo> out_bind_infos;
+    InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
+                              &out_bind_infos);
+    return GetData(device).driver.BindImageMemory2(
+        device, bindInfoCount,
+        out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
+}
+
+VKAPI_ATTR
+VkResult BindImageMemory2KHR(VkDevice device,
+                             uint32_t bindInfoCount,
+                             const VkBindImageMemoryInfo* pBindInfos) {
+    ATRACE_CALL();
+
+    std::vector<VkNativeBufferANDROID> out_native_buffers;
+    std::vector<VkBindImageMemoryInfo> out_bind_infos;
+    InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
+                              &out_bind_infos);
+    return GetData(device).driver.BindImageMemory2KHR(
+        device, bindInfoCount,
+        out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
+}
+
 }  // namespace driver
 }  // namespace vulkan
diff --git a/vulkan/libvulkan/swapchain.h b/vulkan/libvulkan/swapchain.h
index ed5718c..4912ef1 100644
--- a/vulkan/libvulkan/swapchain.h
+++ b/vulkan/libvulkan/swapchain.h
@@ -44,6 +44,8 @@
 VKAPI_ATTR void SetHdrMetadataEXT(VkDevice device, uint32_t swapchainCount, const VkSwapchainKHR* pSwapchains, const VkHdrMetadataEXT* pHdrMetadataEXTs);
 VKAPI_ATTR VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, VkSurfaceCapabilities2KHR* pSurfaceCapabilities);
 VKAPI_ATTR VkResult GetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, uint32_t* pSurfaceFormatCount, VkSurfaceFormat2KHR* pSurfaceFormats);
+VKAPI_ATTR VkResult BindImageMemory2(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfo* pBindInfos);
+VKAPI_ATTR VkResult BindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfo* pBindInfos);
 // clang-format on
 
 }  // namespace driver