Merge "Revert "Revert "Revert "SF: Updating permissions checking in Surface Flinger.""""
diff --git a/cmds/bugreportz/bugreportz.cpp b/cmds/bugreportz/bugreportz.cpp
index 75855cf..ded0ed3 100644
--- a/cmds/bugreportz/bugreportz.cpp
+++ b/cmds/bugreportz/bugreportz.cpp
@@ -55,7 +55,7 @@
                 errno = ETIMEDOUT;
             }
             printf("FAIL:Bugreport read terminated abnormally (%s)\n", strerror(errno));
-            break;
+            return EXIT_FAILURE;
         }
 
         // Writes line by line.
@@ -71,8 +71,5 @@
     // Process final line, in case it didn't finish with newline
     write_line(line, show_progress);
 
-    if (close(s) == -1) {
-        fprintf(stderr, "WARNING: error closing socket: %s\n", strerror(errno));
-    }
     return EXIT_SUCCESS;
 }
diff --git a/cmds/bugreportz/bugreportz.h b/cmds/bugreportz/bugreportz.h
index 304e4b3..7af289b 100644
--- a/cmds/bugreportz/bugreportz.h
+++ b/cmds/bugreportz/bugreportz.h
@@ -16,6 +16,7 @@
 #define BUGREPORTZ_H
 
 // Calls dumpstate using the given socket and output its result to stdout.
+// Ownership of the socket is not transferred.
 int bugreportz(int s, bool show_progress);
 
 #endif  // BUGREPORTZ_H
diff --git a/cmds/bugreportz/main.cpp b/cmds/bugreportz/main.cpp
index a3ae1ff..74a95b0 100644
--- a/cmds/bugreportz/main.cpp
+++ b/cmds/bugreportz/main.cpp
@@ -82,7 +82,7 @@
 
     if (s == -1) {
         printf("FAIL:Failed to connect to dumpstatez service: %s\n", strerror(errno));
-        return EXIT_SUCCESS;
+        return EXIT_FAILURE;
     }
 
     // Set a timeout so that if nothing is read in 10 minutes, we'll stop
@@ -92,8 +92,16 @@
     tv.tv_sec = 10 * 60;
     tv.tv_usec = 0;
     if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == -1) {
-        fprintf(stderr, "WARNING: Cannot set socket timeout: %s\n", strerror(errno));
+        fprintf(stderr,
+                "WARNING: Cannot set socket timeout, bugreportz might hang indefinitely: %s\n",
+                strerror(errno));
     }
 
-    bugreportz(s, show_progress);
+    int ret = bugreportz(s, show_progress);
+
+    if (close(s) == -1) {
+        fprintf(stderr, "WARNING: error closing socket: %s\n", strerror(errno));
+        ret = EXIT_FAILURE;
+    }
+    return ret;
 }
diff --git a/libs/dumputils/dump_utils.cpp b/libs/dumputils/dump_utils.cpp
index 8b2f842..0d224d8 100644
--- a/libs/dumputils/dump_utils.cpp
+++ b/libs/dumputils/dump_utils.cpp
@@ -46,6 +46,7 @@
         "android.hardware.bluetooth@1.0::IBluetoothHci",
         "android.hardware.camera.provider@2.4::ICameraProvider",
         "android.hardware.drm@1.0::IDrmFactory",
+        "android.hardware.graphics.allocator@2.0::IAllocator",
         "android.hardware.graphics.composer@2.1::IComposer",
         "android.hardware.media.omx@1.0::IOmx",
         "android.hardware.media.omx@1.0::IOmxStore",
diff --git a/libs/ui/Android.bp b/libs/ui/Android.bp
index d25ad1a..e3ef2a9 100644
--- a/libs/ui/Android.bp
+++ b/libs/ui/Android.bp
@@ -65,6 +65,7 @@
         "PixelFormat.cpp",
         "Rect.cpp",
         "Region.cpp",
+        "Transform.cpp",
         "UiConfig.cpp",
     ],
 
diff --git a/services/surfaceflinger/Transform.cpp b/libs/ui/Transform.cpp
similarity index 81%
rename from services/surfaceflinger/Transform.cpp
rename to libs/ui/Transform.cpp
index e05ed53..8e949ec 100644
--- a/services/surfaceflinger/Transform.cpp
+++ b/libs/ui/Transform.cpp
@@ -17,17 +17,12 @@
 #include <math.h>
 
 #include <cutils/compiler.h>
-#include <utils/String8.h>
 #include <ui/Region.h>
-
-#include "Transform.h"
-#include "clz.h"
-
-// ---------------------------------------------------------------------------
+#include <ui/Transform.h>
+#include <utils/String8.h>
 
 namespace android {
-
-// ---------------------------------------------------------------------------
+namespace ui {
 
 Transform::Transform() {
     reset();
@@ -41,8 +36,7 @@
     set(orientation, 0, 0);
 }
 
-Transform::~Transform() {
-}
+Transform::~Transform() = default;
 
 static const float EPSILON = 0.0f;
 
@@ -67,7 +61,7 @@
     const mat33& A(mMatrix);
     const mat33& B(rhs.mMatrix);
           mat33& D(r.mMatrix);
-    for (int i=0 ; i<3 ; i++) {
+    for (size_t i = 0; i < 3; i++) {
         const float v0 = A[0][i];
         const float v1 = A[1][i];
         const float v2 = A[2][i];
@@ -83,6 +77,12 @@
     return r;
 }
 
+Transform& Transform::operator=(const Transform& other) {
+    mMatrix = other.mMatrix;
+    mType = other.mType;
+    return *this;
+}
+
 const vec3& Transform::operator [] (size_t i) const {
     return mMatrix[i];
 }
@@ -97,10 +97,10 @@
 
 void Transform::reset() {
     mType = IDENTITY;
-    for(int i=0 ; i<3 ; i++) {
+    for(size_t i = 0; i < 3; i++) {
         vec3& v(mMatrix[i]);
-        for (int j=0 ; j<3 ; j++)
-            v[j] = ((i==j) ? 1.0f : 0.0f);
+        for (size_t j = 0; j < 3; j++)
+            v[j] = ((i == j) ? 1.0f : 0.0f);
     }
 }
 
@@ -137,7 +137,7 @@
     Transform H, V, R;
     if (flags & ROT_90) {
         // w & h are inverted when rotating by 90 degrees
-        swap(w, h);
+        std::swap(w, h);
     }
 
     if (flags & FLIP_H) {
@@ -210,15 +210,15 @@
     rb = transform(rb);
 
     if (roundOutwards) {
-        r.left   = floorf(min(lt[0], rt[0], lb[0], rb[0]));
-        r.top    = floorf(min(lt[1], rt[1], lb[1], rb[1]));
-        r.right  = ceilf(max(lt[0], rt[0], lb[0], rb[0]));
-        r.bottom = ceilf(max(lt[1], rt[1], lb[1], rb[1]));
+        r.left   = static_cast<int32_t>(floorf(std::min({lt[0], rt[0], lb[0], rb[0]})));
+        r.top    = static_cast<int32_t>(floorf(std::min({lt[1], rt[1], lb[1], rb[1]})));
+        r.right  = static_cast<int32_t>(ceilf(std::max({lt[0], rt[0], lb[0], rb[0]})));
+        r.bottom = static_cast<int32_t>(ceilf(std::max({lt[1], rt[1], lb[1], rb[1]})));
     } else {
-        r.left   = floorf(min(lt[0], rt[0], lb[0], rb[0]) + 0.5f);
-        r.top    = floorf(min(lt[1], rt[1], lb[1], rb[1]) + 0.5f);
-        r.right  = floorf(max(lt[0], rt[0], lb[0], rb[0]) + 0.5f);
-        r.bottom = floorf(max(lt[1], rt[1], lb[1], rb[1]) + 0.5f);
+        r.left   = static_cast<int32_t>(floorf(std::min({lt[0], rt[0], lb[0], rb[0]}) + 0.5f));
+        r.top    = static_cast<int32_t>(floorf(std::min({lt[1], rt[1], lb[1], rb[1]}) + 0.5f));
+        r.right  = static_cast<int32_t>(floorf(std::max({lt[0], rt[0], lb[0], rb[0]}) + 0.5f));
+        r.bottom = static_cast<int32_t>(floorf(std::max({lt[1], rt[1], lb[1], rb[1]}) + 0.5f));
     }
 
     return r;
@@ -237,10 +237,10 @@
     rb = transform(rb);
 
     FloatRect r;
-    r.left = min(lt[0], rt[0], lb[0], rb[0]);
-    r.top = min(lt[1], rt[1], lb[1], rb[1]);
-    r.right = max(lt[0], rt[0], lb[0], rb[0]);
-    r.bottom = max(lt[1], rt[1], lb[1], rb[1]);
+    r.left = std::min({lt[0], rt[0], lb[0], rb[0]});
+    r.top = std::min({lt[1], rt[1], lb[1], rb[1]});
+    r.right = std::max({lt[0], rt[0], lb[0], rb[0]});
+    r.bottom = std::max({lt[1], rt[1], lb[1], rb[1]});
 
     return r;
 }
@@ -259,8 +259,8 @@
             out.set(transform(reg.bounds()));
         }
     } else {
-        int xpos = floorf(tx() + 0.5f);
-        int ypos = floorf(ty() + 0.5f);
+        int xpos = static_cast<int>(floorf(tx() + 0.5f));
+        int ypos = static_cast<int>(floorf(ty() + 0.5f));
         out = reg.translate(xpos, ypos);
     }
     return out;
@@ -343,7 +343,7 @@
         const float x = M[2][0];
         const float y = M[2][1];
 
-        const float idet = 1.0 / (a*d - b*c);
+        const float idet = 1.0f / (a*d - b*c);
         result.mMatrix[0][0] =  d*idet;
         result.mMatrix[0][1] = -c*idet;
         result.mMatrix[1][0] = -b*idet;
@@ -404,28 +404,13 @@
         type.append("TRANSLATE ");
 
     ALOGD("%s 0x%08x (%s, %s)", name, mType, flags.string(), type.string());
-    ALOGD("%.4f  %.4f  %.4f", m[0][0], m[1][0], m[2][0]);
-    ALOGD("%.4f  %.4f  %.4f", m[0][1], m[1][1], m[2][1]);
-    ALOGD("%.4f  %.4f  %.4f", m[0][2], m[1][2], m[2][2]);
+    ALOGD("%.4f  %.4f  %.4f", static_cast<double>(m[0][0]), static_cast<double>(m[1][0]),
+          static_cast<double>(m[2][0]));
+    ALOGD("%.4f  %.4f  %.4f", static_cast<double>(m[0][1]), static_cast<double>(m[1][1]),
+          static_cast<double>(m[2][1]));
+    ALOGD("%.4f  %.4f  %.4f", static_cast<double>(m[0][2]), static_cast<double>(m[1][2]),
+          static_cast<double>(m[2][2]));
 }
 
-Transform::orientation_flags Transform::fromRotation(ISurfaceComposer::Rotation rotation) {
-    // Convert to surfaceflinger's internal rotation type.
-    switch (rotation) {
-        case ISurfaceComposer::eRotateNone:
-            return Transform::ROT_0;
-        case ISurfaceComposer::eRotate90:
-            return Transform::ROT_90;
-        case ISurfaceComposer::eRotate180:
-            return Transform::ROT_180;
-        case ISurfaceComposer::eRotate270:
-            return Transform::ROT_270;
-        default:
-            ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
-            return Transform::ROT_0;
-    }
-}
-
-// ---------------------------------------------------------------------------
-
-}; // namespace android
+}  // namespace ui
+}  // namespace android
diff --git a/libs/ui/include/ui/Transform.h b/libs/ui/include/ui/Transform.h
new file mode 100644
index 0000000..42dca75
--- /dev/null
+++ b/libs/ui/include/ui/Transform.h
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2007 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.
+ */
+
+#ifndef ANDROID_TRANSFORM_H
+#define ANDROID_TRANSFORM_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <hardware/hardware.h>
+#include <math/vec2.h>
+#include <math/vec3.h>
+#include <ui/Point.h>
+#include <ui/Rect.h>
+
+namespace android {
+
+class Region;
+
+namespace ui {
+
+class Transform {
+public:
+    Transform();
+    Transform(const Transform&  other);
+    explicit Transform(uint32_t orientation);
+    ~Transform();
+
+    enum orientation_flags {
+        ROT_0   = 0x00000000,
+        FLIP_H  = HAL_TRANSFORM_FLIP_H,
+        FLIP_V  = HAL_TRANSFORM_FLIP_V,
+        ROT_90  = HAL_TRANSFORM_ROT_90,
+        ROT_180 = FLIP_H|FLIP_V,
+        ROT_270 = ROT_180|ROT_90,
+        ROT_INVALID = 0x80
+    };
+
+    enum type_mask : uint32_t {
+        IDENTITY            = 0,
+        TRANSLATE           = 0x1,
+        ROTATE              = 0x2,
+        SCALE               = 0x4,
+        UNKNOWN             = 0x8
+    };
+
+    // query the transform
+    bool        preserveRects() const;
+    uint32_t    getType() const;
+    uint32_t    getOrientation() const;
+
+    const vec3& operator [] (size_t i) const;  // returns column i
+    float   tx() const;
+    float   ty() const;
+
+    // modify the transform
+    void        reset();
+    void        set(float tx, float ty);
+    void        set(float a, float b, float c, float d);
+    status_t    set(uint32_t flags, float w, float h);
+
+    // transform data
+    Rect    makeBounds(int w, int h) const;
+    vec2    transform(int x, int y) const;
+    Region  transform(const Region& reg) const;
+    Rect    transform(const Rect& bounds,
+                      bool roundOutwards = false) const;
+    FloatRect transform(const FloatRect& bounds) const;
+    Transform& operator = (const Transform& other);
+    Transform operator * (const Transform& rhs) const;
+    // assumes the last row is < 0 , 0 , 1 >
+    vec2 transform(const vec2& v) const;
+    vec3 transform(const vec3& v) const;
+
+    Transform inverse() const;
+
+    // for debugging
+    void dump(const char* name) const;
+
+private:
+    struct mat33 {
+        vec3 v[3];
+        inline const vec3& operator [] (size_t i) const { return v[i]; }
+        inline vec3& operator [] (size_t i) { return v[i]; }
+    };
+
+    enum { UNKNOWN_TYPE = 0x80000000 };
+
+    uint32_t type() const;
+    static bool absIsOne(float f);
+    static bool isZero(float f);
+
+    mat33               mMatrix;
+    mutable uint32_t    mType;
+};
+
+}  // namespace ui
+}  // namespace android
+
+#endif /* ANDROID_TRANSFORM_H */
diff --git a/libs/vr/CleanSpec.mk b/libs/vr/CleanSpec.mk
new file mode 100644
index 0000000..a17c9b2
--- /dev/null
+++ b/libs/vr/CleanSpec.mk
@@ -0,0 +1,52 @@
+# Copyright (C) 2012 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.
+#
+
+# If you don't need to do a full clean build but would like to touch
+# a file or delete some intermediate files, add a clean step to the end
+# of the list.  These steps will only be run once, if they haven't been
+# run before.
+#
+# E.g.:
+#     $(call add-clean-step, touch -c external/sqlite/sqlite3.h)
+#     $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libz_intermediates)
+#
+# Always use "touch -c" and "rm -f" or "rm -rf" to gracefully deal with
+# files that are missing or have been moved.
+#
+# Use $(PRODUCT_OUT) to get to the "out/target/product/blah/" directory.
+# Use $(OUT_DIR) to refer to the "out" directory.
+#
+# If you need to re-do something that's already mentioned, just copy
+# the command and add it to the bottom of the list.  E.g., if a change
+# that you made last week required touching a file and a change you
+# made today requires touching the same file, just copy the old
+# touch step and add it to the end of the list.
+#
+# ************************************************
+# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
+# ************************************************
+
+# For example:
+#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/AndroidTests_intermediates)
+#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/core_intermediates)
+#$(call add-clean-step, find $(OUT_DIR) -type f -name "IGTalkSession*" -print0 | xargs -0 rm -f)
+#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*)
+
+# ************************************************
+# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
+# ************************************************
+$(call add-clean-step, find $(PRODUCT_OUT) -type f -name "libdvr.so" -print0 | xargs -0 rm -f)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libdvr_intermediates)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libdvr_intermediates)
diff --git a/libs/vr/libbufferhub/buffer_hub-test.cpp b/libs/vr/libbufferhub/buffer_hub-test.cpp
index 2a962b5..2ab5b65 100644
--- a/libs/vr/libbufferhub/buffer_hub-test.cpp
+++ b/libs/vr/libbufferhub/buffer_hub-test.cpp
@@ -968,8 +968,19 @@
   ASSERT_TRUE(b2 != nullptr);
   int b2_id = b2->id();
 
-  // The duplicated buffer should inherit the same buffer id.
+  // These two buffer instances are based on the same physical buffer under the
+  // hood, so they should share the same id.
   EXPECT_EQ(b1_id, b2_id);
+  // We use buffer_state_bit() to tell those two instances apart.
+  EXPECT_NE(b1->buffer_state_bit(), b2->buffer_state_bit());
+  EXPECT_NE(b1->buffer_state_bit(), 0ULL);
+  EXPECT_NE(b2->buffer_state_bit(), 0ULL);
+  EXPECT_NE(b1->buffer_state_bit(), kProducerStateBit);
+  EXPECT_NE(b2->buffer_state_bit(), kProducerStateBit);
+
+  // Both buffer instances should be in gained state.
+  EXPECT_TRUE(IsBufferGained(b1->buffer_state()));
+  EXPECT_TRUE(IsBufferGained(b2->buffer_state()));
 
   // Promote the detached buffer should fail as b1 is no longer the exclusive
   // owner of the buffer..
diff --git a/libs/vr/libbufferhub/detached_buffer.cpp b/libs/vr/libbufferhub/detached_buffer.cpp
index 60f11e2..02abd91 100644
--- a/libs/vr/libbufferhub/detached_buffer.cpp
+++ b/libs/vr/libbufferhub/detached_buffer.cpp
@@ -49,7 +49,7 @@
 }
 
 int DetachedBuffer::ImportGraphicBuffer() {
-  ATRACE_NAME("DetachedBuffer::DetachedBuffer");
+  ATRACE_NAME("DetachedBuffer::ImportGraphicBuffer");
 
   auto status = client_.InvokeRemoteMethod<DetachedBufferRPC::Import>();
   if (!status) {
@@ -76,9 +76,53 @@
     return ret;
   }
 
+  // Import the metadata.
+  IonBuffer metadata_buffer;
+  if (const int ret = buffer_desc.ImportMetadata(&metadata_buffer)) {
+    ALOGE("Failed to import metadata buffer, error=%d", ret);
+    return ret;
+  }
+  size_t metadata_buf_size = metadata_buffer.width();
+  if (metadata_buf_size < BufferHubDefs::kMetadataHeaderSize) {
+    ALOGE("DetachedBuffer::ImportGraphicBuffer: metadata buffer too small: %zu",
+          metadata_buf_size);
+    return -EINVAL;
+  }
+
   // If all imports succeed, replace the previous buffer and id.
   id_ = buffer_id;
   buffer_ = std::move(ion_buffer);
+  metadata_buffer_ = std::move(metadata_buffer);
+  user_metadata_size_ = metadata_buf_size - BufferHubDefs::kMetadataHeaderSize;
+
+  void* metadata_ptr = nullptr;
+  if (const int ret =
+          metadata_buffer_.Lock(BufferHubDefs::kMetadataUsage, /*x=*/0,
+                                /*y=*/0, metadata_buf_size,
+                                /*height=*/1, &metadata_ptr)) {
+    ALOGE("DetachedBuffer::ImportGraphicBuffer: Failed to lock metadata.");
+    return ret;
+  }
+
+  // TODO(b/112012161) Set up shared fences.
+
+  // Note that here the buffer state is mapped from shared memory as an atomic
+  // object. The std::atomic's constructor will not be called so that the
+  // original value stored in the memory region can be preserved.
+  metadata_header_ = static_cast<BufferHubDefs::MetadataHeader*>(metadata_ptr);
+  if (user_metadata_size_) {
+    user_metadata_ptr_ = static_cast<void*>(metadata_header_ + 1);
+  } else {
+    user_metadata_ptr_ = nullptr;
+  }
+
+  id_ = buffer_desc.id();
+  buffer_state_bit_ = buffer_desc.buffer_state_bit();
+
+  ALOGD_IF(TRACE,
+           "DetachedBuffer::ImportGraphicBuffer: id=%d, buffer_state=%" PRIx64
+           ".",
+           id(), metadata_header_->buffer_state.load());
   return 0;
 }
 
diff --git a/libs/vr/libbufferhub/include/private/dvr/detached_buffer.h b/libs/vr/libbufferhub/include/private/dvr/detached_buffer.h
index 376b53e..1fc011b 100644
--- a/libs/vr/libbufferhub/include/private/dvr/detached_buffer.h
+++ b/libs/vr/libbufferhub/include/private/dvr/detached_buffer.h
@@ -30,8 +30,17 @@
 
   const sp<GraphicBuffer>& buffer() const { return buffer_.buffer(); }
 
+  // Gets ID of the buffer client. All DetachedBuffer clients derived from the
+  // same buffer in bufferhubd share the same buffer id.
   int id() const { return id_; }
 
+  // Returns the current value of MetadataHeader::buffer_state.
+  uint64_t buffer_state() { return metadata_header_->buffer_state.load(); }
+
+  // A state mask which is unique to a buffer hub client among all its siblings
+  // sharing the same concrete graphic buffer.
+  uint64_t buffer_state_bit() const { return buffer_state_bit_; }
+
   // Returns true if the buffer holds an open PDX channels towards bufferhubd.
   bool IsConnected() const { return client_.IsValid(); }
 
@@ -75,7 +84,18 @@
 
   // Global id for the buffer that is consistent across processes.
   int id_;
+  uint64_t buffer_state_bit_;
+
+  // The concrete Ion buffers.
   IonBuffer buffer_;
+  IonBuffer metadata_buffer_;
+
+  // buffer metadata.
+  size_t user_metadata_size_ = 0;
+  BufferHubDefs::MetadataHeader* metadata_header_ = nullptr;
+  void* user_metadata_ptr_ = nullptr;
+
+  // PDX backend.
   BufferHubClient client_;
 };
 
diff --git a/libs/vr/libbufferhubqueue/benchmarks/Android.bp b/libs/vr/libbufferhubqueue/benchmarks/Android.bp
index 5089b87..ef1eed6 100644
--- a/libs/vr/libbufferhubqueue/benchmarks/Android.bp
+++ b/libs/vr/libbufferhubqueue/benchmarks/Android.bp
@@ -5,7 +5,7 @@
         "libbase",
         "libbinder",
         "libcutils",
-        "libdvr",
+        "libdvr.google",
         "libgui",
         "liblog",
         "libhardware",
diff --git a/libs/vr/libbufferhubqueue/benchmarks/buffer_transport_benchmark.cpp b/libs/vr/libbufferhubqueue/benchmarks/buffer_transport_benchmark.cpp
index 4ca8671..b2b4d7a 100644
--- a/libs/vr/libbufferhubqueue/benchmarks/buffer_transport_benchmark.cpp
+++ b/libs/vr/libbufferhubqueue/benchmarks/buffer_transport_benchmark.cpp
@@ -206,7 +206,7 @@
 class DvrApi {
  public:
   DvrApi() {
-    handle_ = dlopen("libdvr.so", RTLD_NOW | RTLD_LOCAL);
+    handle_ = dlopen("libdvr.google.so", RTLD_NOW | RTLD_LOCAL);
     CHECK(handle_);
 
     auto dvr_get_api =
diff --git a/libs/vr/libdvr/Android.bp b/libs/vr/libdvr/Android.bp
index 3829951..81a9b2d 100644
--- a/libs/vr/libdvr/Android.bp
+++ b/libs/vr/libdvr/Android.bp
@@ -73,7 +73,7 @@
 ]
 
 cc_library_shared {
-    name: "libdvr",
+    name: "libdvr.google",
     owner: "google",
     cflags: cflags,
     header_libs: ["libdvr_headers"],
@@ -88,7 +88,7 @@
 // restricting function access in the shared lib makes it inconvenient to use in
 // test code.
 cc_library_static {
-    name: "libdvr_static",
+    name: "libdvr_static.google",
     owner: "google",
     cflags: cflags,
     header_libs: ["libdvr_headers"],
diff --git a/libs/vr/libdvr/tests/Android.bp b/libs/vr/libdvr/tests/Android.bp
index b23a0fa..3260447 100644
--- a/libs/vr/libdvr/tests/Android.bp
+++ b/libs/vr/libdvr/tests/Android.bp
@@ -21,7 +21,7 @@
 
     header_libs: ["libdvr_headers"],
     static_libs: [
-        "libdvr_static",
+        "libdvr_static.google",
         "libchrome",
         "libdvrcommon",
         "libdisplay",
diff --git a/libs/vr/libdvr/tests/dvr_api_test.h b/libs/vr/libdvr/tests/dvr_api_test.h
index d8359e7..5d2ec28 100644
--- a/libs/vr/libdvr/tests/dvr_api_test.h
+++ b/libs/vr/libdvr/tests/dvr_api_test.h
@@ -14,7 +14,7 @@
     // workaround for an Android NDK bug. See more detail:
     // https://github.com/android-ndk/ndk/issues/360
     flags |= RTLD_NODELETE;
-    platform_handle_ = dlopen("libdvr.so", flags);
+    platform_handle_ = dlopen("libdvr.google.so", flags);
     ASSERT_NE(nullptr, platform_handle_) << "Dvr shared library missing.";
 
     auto dvr_get_api = reinterpret_cast<decltype(&dvrGetApi)>(
diff --git a/libs/vr/public.libraries-google.txt b/libs/vr/public.libraries-google.txt
new file mode 100644
index 0000000..8271b94
--- /dev/null
+++ b/libs/vr/public.libraries-google.txt
@@ -0,0 +1 @@
+libdvr.google.so
\ No newline at end of file
diff --git a/services/inputflinger/InputDispatcher.cpp b/services/inputflinger/InputDispatcher.cpp
index 863e426..c805805 100644
--- a/services/inputflinger/InputDispatcher.cpp
+++ b/services/inputflinger/InputDispatcher.cpp
@@ -515,10 +515,9 @@
 sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
         int32_t x, int32_t y) {
     // Traverse windows from front to back to find touched window.
-    const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
-    size_t numWindows = windowHandles.size();
+    size_t numWindows = mWindowHandles.size();
     for (size_t i = 0; i < numWindows; i++) {
-        sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
+        sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
         const InputWindowInfo* windowInfo = windowHandle->getInfo();
         if (windowInfo->displayId == displayId) {
             int32_t flags = windowInfo->layoutParamsFlags;
@@ -1248,10 +1247,9 @@
         bool isTouchModal = false;
 
         // Traverse windows from front to back to find touched window and outside targets.
-        const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
-        size_t numWindows = windowHandles.size();
+        size_t numWindows = mWindowHandles.size();
         for (size_t i = 0; i < numWindows; i++) {
-            sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
+            sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
             const InputWindowInfo* windowInfo = windowHandle->getInfo();
             if (windowInfo->displayId != displayId) {
                 continue; // wrong display
@@ -1474,10 +1472,8 @@
         sp<InputWindowHandle> foregroundWindowHandle =
                 mTempTouchState.getFirstForegroundWindowHandle();
         if (foregroundWindowHandle->getInfo()->hasWallpaper) {
-            const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
-            size_t numWindows = windowHandles.size();
-            for (size_t i = 0; i < numWindows; i++) {
-                sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
+            for (size_t i = 0; i < mWindowHandles.size(); i++) {
+                sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
                 const InputWindowInfo* info = windowHandle->getInfo();
                 if (info->displayId == displayId
                         && windowHandle->getInfo()->layoutParamsType
@@ -1662,10 +1658,9 @@
 bool InputDispatcher::isWindowObscuredAtPointLocked(
         const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
     int32_t displayId = windowHandle->getInfo()->displayId;
-    const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
-    size_t numWindows = windowHandles.size();
+    size_t numWindows = mWindowHandles.size();
     for (size_t i = 0; i < numWindows; i++) {
-        sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
+        sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
         if (otherHandle == windowHandle) {
             break;
         }
@@ -1683,11 +1678,10 @@
 
 bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
     int32_t displayId = windowHandle->getInfo()->displayId;
-    const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
     const InputWindowInfo* windowInfo = windowHandle->getInfo();
-    size_t numWindows = windowHandles.size();
+    size_t numWindows = mWindowHandles.size();
     for (size_t i = 0; i < numWindows; i++) {
-        sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
+        sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
         if (otherHandle == windowHandle) {
             break;
         }
@@ -2915,77 +2909,52 @@
     }
 }
 
-Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
-    std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it
-        = mWindowHandlesByDisplay.find(displayId);
-    if(it != mWindowHandlesByDisplay.end()) {
-        return it->second;
-    }
-
-    // Return an empty one if nothing found.
-    return Vector<sp<InputWindowHandle>>();
-}
-
 sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
         const sp<InputChannel>& inputChannel) const {
-    for (auto& it : mWindowHandlesByDisplay) {
-        const Vector<sp<InputWindowHandle>> windowHandles = it.second;
-        size_t numWindows = windowHandles.size();
-        for (size_t i = 0; i < numWindows; i++) {
-            const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
-            if (windowHandle->getInputChannel() == inputChannel) {
-                return windowHandle;
-            }
+    size_t numWindows = mWindowHandles.size();
+    for (size_t i = 0; i < numWindows; i++) {
+        const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
+        if (windowHandle->getInputChannel() == inputChannel) {
+            return windowHandle;
         }
     }
     return nullptr;
 }
 
 bool InputDispatcher::hasWindowHandleLocked(
-        const sp<InputWindowHandle>& windowHandle, int32_t displayId) const {
-
-    const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
-    size_t numWindows = windowHandles.size();
+        const sp<InputWindowHandle>& windowHandle) const {
+    size_t numWindows = mWindowHandles.size();
     for (size_t i = 0; i < numWindows; i++) {
-        if (windowHandles.itemAt(i) == windowHandle) {
+        if (mWindowHandles.itemAt(i) == windowHandle) {
             return true;
         }
     }
     return false;
 }
 
-void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
-        int displayId) {
+void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
 #if DEBUG_FOCUS
     ALOGD("setInputWindows");
 #endif
     { // acquire lock
         AutoMutex _l(mLock);
 
-        const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
-        Vector<sp<InputWindowHandle>> windowHandles = inputWindowHandles;
-        // Insert or replace
-        mWindowHandlesByDisplay[displayId] = windowHandles;
+        Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
+        mWindowHandles = inputWindowHandles;
 
-        // TODO(b/111361570): multi-display focus, one focus in all display in current.
-        sp<InputWindowHandle> newFocusedWindowHandle = mFocusedWindowHandle;
+        sp<InputWindowHandle> newFocusedWindowHandle;
         bool foundHoveredWindow = false;
-
-        if (windowHandles.isEmpty()) {
-            // Remove all handles on a display if there are no windows left.
-            mWindowHandlesByDisplay.erase(displayId);
-        } else {
-            for (size_t i = 0; i < windowHandles.size(); i++) {
-                const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
-                if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == nullptr) {
-                    continue;
-                }
-                if (windowHandle->getInfo()->hasFocus) {
-                    newFocusedWindowHandle = windowHandle;
-                }
-                if (windowHandle == mLastHoverWindowHandle) {
-                    foundHoveredWindow = true;
-                }
+        for (size_t i = 0; i < mWindowHandles.size(); i++) {
+            const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
+            if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == nullptr) {
+                mWindowHandles.removeAt(i--);
+                continue;
+            }
+            if (windowHandle->getInfo()->hasFocus) {
+                newFocusedWindowHandle = windowHandle;
+            }
+            if (windowHandle == mLastHoverWindowHandle) {
+                foundHoveredWindow = true;
             }
         }
 
@@ -2993,7 +2962,6 @@
             mLastHoverWindowHandle = nullptr;
         }
 
-        // TODO(b/111361570): multi-display focus, one focus in all display in current.
         if (mFocusedWindowHandle != newFocusedWindowHandle) {
             if (mFocusedWindowHandle != nullptr) {
 #if DEBUG_FOCUS
@@ -3017,12 +2985,11 @@
             mFocusedWindowHandle = newFocusedWindowHandle;
         }
 
-        ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
-        if (stateIndex >= 0) {
-            TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
+        for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
+            TouchState& state = mTouchStatesByDisplay.editValueAt(d);
             for (size_t i = 0; i < state.windows.size(); ) {
                 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
-                if (!hasWindowHandleLocked(touchedWindow.windowHandle, displayId)) {
+                if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
 #if DEBUG_FOCUS
                     ALOGD("Touched window was removed: %s",
                             touchedWindow.windowHandle->getName().c_str());
@@ -3048,7 +3015,7 @@
         // which might not happen until the next GC.
         for (size_t i = 0; i < oldWindowHandles.size(); i++) {
             const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
-            if (!hasWindowHandleLocked(oldWindowHandle, displayId)) {
+            if (!hasWindowHandleLocked(oldWindowHandle)) {
 #if DEBUG_FOCUS
                 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
 #endif
@@ -3299,44 +3266,36 @@
         dump += INDENT "TouchStates: <no displays touched>\n";
     }
 
-    if (!mWindowHandlesByDisplay.empty()) {
-       for (auto& it : mWindowHandlesByDisplay) {
-            const Vector<sp<InputWindowHandle>> windowHandles = it.second;
-            dump += StringPrintf(INDENT "Display: %d\n", it.first);
-            if (!windowHandles.isEmpty()) {
-                dump += INDENT "Windows:\n";
-                for (size_t i = 0; i < windowHandles.size(); i++) {
-                    const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
-                    const InputWindowInfo* windowInfo = windowHandle->getInfo();
+    if (!mWindowHandles.isEmpty()) {
+        dump += INDENT "Windows:\n";
+        for (size_t i = 0; i < mWindowHandles.size(); i++) {
+            const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
+            const InputWindowInfo* windowInfo = windowHandle->getInfo();
 
-                    dump += StringPrintf(INDENT2 "%zu: name='%s', displayId=%d, "
-                            "paused=%s, hasFocus=%s, hasWallpaper=%s, "
-                            "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
-                            "frame=[%d,%d][%d,%d], scale=%f, "
-                            "touchableRegion=",
-                            i, windowInfo->name.c_str(), windowInfo->displayId,
-                            toString(windowInfo->paused),
-                            toString(windowInfo->hasFocus),
-                            toString(windowInfo->hasWallpaper),
-                            toString(windowInfo->visible),
-                            toString(windowInfo->canReceiveKeys),
-                            windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
-                            windowInfo->layer,
-                            windowInfo->frameLeft, windowInfo->frameTop,
-                            windowInfo->frameRight, windowInfo->frameBottom,
-                            windowInfo->scaleFactor);
-                    dumpRegion(dump, windowInfo->touchableRegion);
-                    dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
-                    dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
-                            windowInfo->ownerPid, windowInfo->ownerUid,
-                            windowInfo->dispatchingTimeout / 1000000.0);
-                }
-            } else {
-                dump += INDENT "Windows: <none>\n";
-            }
+            dump += StringPrintf(INDENT2 "%zu: name='%s', displayId=%d, "
+                    "paused=%s, hasFocus=%s, hasWallpaper=%s, "
+                    "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
+                    "frame=[%d,%d][%d,%d], scale=%f, "
+                    "touchableRegion=",
+                    i, windowInfo->name.c_str(), windowInfo->displayId,
+                    toString(windowInfo->paused),
+                    toString(windowInfo->hasFocus),
+                    toString(windowInfo->hasWallpaper),
+                    toString(windowInfo->visible),
+                    toString(windowInfo->canReceiveKeys),
+                    windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
+                    windowInfo->layer,
+                    windowInfo->frameLeft, windowInfo->frameTop,
+                    windowInfo->frameRight, windowInfo->frameBottom,
+                    windowInfo->scaleFactor);
+            dumpRegion(dump, windowInfo->touchableRegion);
+            dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
+            dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
+                    windowInfo->ownerPid, windowInfo->ownerUid,
+                    windowInfo->dispatchingTimeout / 1000000.0);
         }
     } else {
-        dump += INDENT "Displays: <none>\n";
+        dump += INDENT "Windows: <none>\n";
     }
 
     if (!mMonitoringChannels.isEmpty()) {
diff --git a/services/inputflinger/InputDispatcher.h b/services/inputflinger/InputDispatcher.h
index 5cb7fe1..31ab339 100644
--- a/services/inputflinger/InputDispatcher.h
+++ b/services/inputflinger/InputDispatcher.h
@@ -31,7 +31,6 @@
 #include <stddef.h>
 #include <unistd.h>
 #include <limits.h>
-#include <unordered_map>
 
 #include "InputWindow.h"
 #include "InputApplication.h"
@@ -308,8 +307,7 @@
      *
      * This method may be called on any thread (usually by the input manager).
      */
-    virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
-            int displayId) = 0;
+    virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) = 0;
 
     /* Sets the focused application.
      *
@@ -389,8 +387,7 @@
             int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
             uint32_t policyFlags);
 
-    virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
-            int displayId);
+    virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles);
     virtual void setFocusedApplication(const sp<InputApplicationHandle>& inputApplicationHandle);
     virtual void setInputDispatchMode(bool enabled, bool frozen);
     virtual void setInputFilterEnabled(bool enabled);
@@ -959,11 +956,10 @@
     bool mDispatchFrozen;
     bool mInputFilterEnabled;
 
-    std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>> mWindowHandlesByDisplay;
-    // Get window handles by display, return an empty vector if not found.
-    Vector<sp<InputWindowHandle>> getWindowHandlesLocked(int32_t displayId) const;
+    Vector<sp<InputWindowHandle> > mWindowHandles;
+
     sp<InputWindowHandle> getWindowHandleLocked(const sp<InputChannel>& inputChannel) const;
-    bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle, int32_t displayId) const;
+    bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const;
 
     // Focus tracking for keys, trackball, etc.
     sp<InputWindowHandle> mFocusedWindowHandle;
diff --git a/services/surfaceflinger/Android.bp b/services/surfaceflinger/Android.bp
index d0aa742..efaeaa2 100644
--- a/services/surfaceflinger/Android.bp
+++ b/services/surfaceflinger/Android.bp
@@ -128,6 +128,7 @@
         "RenderEngine/Surface.cpp",
         "RenderEngine/Texture.cpp",
         "Scheduler/DispSync.cpp",
+        "Scheduler/DispSyncSource.cpp",
         "Scheduler/EventControlThread.cpp",
         "Scheduler/EventThread.cpp",
         "Scheduler/MessageQueue.cpp",
@@ -136,7 +137,6 @@
         "SurfaceInterceptor.cpp",
         "SurfaceTracing.cpp",
         "TimeStats/TimeStats.cpp",
-        "Transform.cpp",
     ],
 }
 
diff --git a/services/surfaceflinger/BufferLayer.cpp b/services/surfaceflinger/BufferLayer.cpp
index e724666..e1094d8 100644
--- a/services/surfaceflinger/BufferLayer.cpp
+++ b/services/surfaceflinger/BufferLayer.cpp
@@ -23,7 +23,6 @@
 #include "Colorizer.h"
 #include "DisplayDevice.h"
 #include "LayerRejecter.h"
-#include "clz.h"
 
 #include "RenderEngine/RenderEngine.h"
 
@@ -259,7 +258,7 @@
 void BufferLayer::setPerFrameData(const sp<const DisplayDevice>& display) {
     // Apply this display's projection's viewport to the visible region
     // before giving it to the HWC HAL.
-    const Transform& tr = display->getTransform();
+    const ui::Transform& tr = display->getTransform();
     const auto& viewport = display->getViewport();
     Region visible = tr.transform(visibleRegion.intersect(viewport));
     const auto displayId = display->getId();
@@ -639,7 +638,7 @@
      */
     const Rect bounds{computeBounds()}; // Rounds from FloatRect
 
-    Transform t = getTransform();
+    ui::Transform t = getTransform();
     Rect win = bounds;
     Rect finalCrop = getFinalCrop(s);
     if (!finalCrop.isEmpty()) {
diff --git a/services/surfaceflinger/BufferLayer.h b/services/surfaceflinger/BufferLayer.h
index 13f4e83..0b641b7 100644
--- a/services/surfaceflinger/BufferLayer.h
+++ b/services/surfaceflinger/BufferLayer.h
@@ -27,7 +27,6 @@
 #include "RenderEngine/Mesh.h"
 #include "RenderEngine/Texture.h"
 #include "SurfaceFlinger.h"
-#include "Transform.h"
 
 #include <gui/ISurfaceComposerClient.h>
 #include <gui/LayerState.h>
diff --git a/services/surfaceflinger/BufferQueueLayer.cpp b/services/surfaceflinger/BufferQueueLayer.cpp
index 6c339b7..6dd29ba 100644
--- a/services/surfaceflinger/BufferQueueLayer.cpp
+++ b/services/surfaceflinger/BufferQueueLayer.cpp
@@ -16,7 +16,6 @@
 
 #include "BufferQueueLayer.h"
 #include "LayerRejecter.h"
-#include "clz.h"
 
 #include <system/window.h>
 
@@ -449,7 +448,7 @@
 
 status_t BufferQueueLayer::setDefaultBufferProperties(uint32_t w, uint32_t h, PixelFormat format) {
     uint32_t const maxSurfaceDims =
-            min(mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
+          std::min(mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
 
     // never allow a surface larger than what our underlying GL implementation
     // can handle.
diff --git a/services/surfaceflinger/BufferStateLayer.cpp b/services/surfaceflinger/BufferStateLayer.cpp
index 44fa760..369ad89 100644
--- a/services/surfaceflinger/BufferStateLayer.cpp
+++ b/services/surfaceflinger/BufferStateLayer.cpp
@@ -21,7 +21,6 @@
 
 #include "BufferStateLayer.h"
 #include "RenderEngine/Image.h"
-#include "clz.h"
 
 #include <private/gui/SyncFeatures.h>
 
@@ -214,7 +213,7 @@
 
 bool BufferStateLayer::setMatrix(const layer_state_t::matrix22_t& matrix,
                                  bool allowNonRectPreservingTransforms) {
-    Transform t;
+    ui::Transform t;
     t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
 
     if (!allowNonRectPreservingTransforms && !t.preserveRects()) {
@@ -400,14 +399,14 @@
     uint32_t bufferWidth = s.buffer->width;
     uint32_t bufferHeight = s.buffer->height;
 
-    if (s.transform & Transform::ROT_90) {
-        swap(bufferWidth, bufferHeight);
+    if (s.transform & ui::Transform::ROT_90) {
+        std::swap(bufferWidth, bufferHeight);
     }
 
     if (s.transformToDisplayInverse) {
         uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
-        if (invTransform & Transform::ROT_90) {
-            swap(bufferWidth, bufferHeight);
+        if (invTransform & ui::Transform::ROT_90) {
+            std::swap(bufferWidth, bufferHeight);
         }
     }
 
diff --git a/services/surfaceflinger/BufferStateLayer.h b/services/surfaceflinger/BufferStateLayer.h
index 4d7396e..e492375 100644
--- a/services/surfaceflinger/BufferStateLayer.h
+++ b/services/surfaceflinger/BufferStateLayer.h
@@ -52,7 +52,7 @@
 
     uint32_t getActiveWidth(const Layer::State& s) const override { return s.active.w; }
     uint32_t getActiveHeight(const Layer::State& s) const override { return s.active.h; }
-    Transform getActiveTransform(const Layer::State& s) const override {
+    ui::Transform getActiveTransform(const Layer::State& s) const override {
         return s.active.transform;
     }
     Region getActiveTransparentRegion(const Layer::State& s) const override {
diff --git a/services/surfaceflinger/ColorLayer.cpp b/services/surfaceflinger/ColorLayer.cpp
index bac46a3..7eeaabb 100644
--- a/services/surfaceflinger/ColorLayer.cpp
+++ b/services/surfaceflinger/ColorLayer.cpp
@@ -72,7 +72,7 @@
 }
 
 void ColorLayer::setPerFrameData(const sp<const DisplayDevice>& display) {
-    const Transform& tr = display->getTransform();
+    const ui::Transform& tr = display->getTransform();
     const auto& viewport = display->getViewport();
     Region visible = tr.transform(visibleRegion.intersect(viewport));
     const auto displayId = display->getId();
diff --git a/services/surfaceflinger/DisplayDevice.cpp b/services/surfaceflinger/DisplayDevice.cpp
index 4d2b0ea..776b84a 100644
--- a/services/surfaceflinger/DisplayDevice.cpp
+++ b/services/surfaceflinger/DisplayDevice.cpp
@@ -44,7 +44,6 @@
 #include "DisplayHardware/HWC2.h"
 #include "RenderEngine/RenderEngine.h"
 
-#include "clz.h"
 #include "DisplayDevice.h"
 #include "SurfaceFlinger.h"
 #include "Layer.h"
@@ -390,7 +389,7 @@
     size_t h = mDisplayHeight;
     Rect sourceCrop(0, 0, w, h);
     mFlinger->getRenderEngine().setViewportAndProjection(w, h, sourceCrop, h,
-        false, Transform::ROT_0);
+        false, ui::Transform::ROT_0);
 }
 
 const sp<Fence>& DisplayDevice::getClientTargetAcquireFence() const {
@@ -420,7 +419,7 @@
     if (repaintEverything) {
         dirty.set(getBounds());
     } else {
-        const Transform& planeTransform(mGlobalTransform);
+        const ui::Transform& planeTransform(mGlobalTransform);
         dirty = planeTransform.transform(this->dirtyRegion);
         dirty.andSelf(getBounds());
     }
@@ -499,37 +498,37 @@
     uint32_t transform = 0;
     switch (mOrientation) {
         case DisplayState::eOrientationDefault:
-            transform = Transform::ROT_0;
+            transform = ui::Transform::ROT_0;
             break;
         case DisplayState::eOrientation90:
-            transform = Transform::ROT_90;
+            transform = ui::Transform::ROT_90;
             break;
         case DisplayState::eOrientation180:
-            transform = Transform::ROT_180;
+            transform = ui::Transform::ROT_180;
             break;
         case DisplayState::eOrientation270:
-            transform = Transform::ROT_270;
+            transform = ui::Transform::ROT_270;
             break;
     }
     return transform;
 }
 
 status_t DisplayDevice::orientationToTransfrom(
-        int orientation, int w, int h, Transform* tr)
+        int orientation, int w, int h, ui::Transform* tr)
 {
     uint32_t flags = 0;
     switch (orientation) {
     case DisplayState::eOrientationDefault:
-        flags = Transform::ROT_0;
+        flags = ui::Transform::ROT_0;
         break;
     case DisplayState::eOrientation90:
-        flags = Transform::ROT_90;
+        flags = ui::Transform::ROT_90;
         break;
     case DisplayState::eOrientation180:
-        flags = Transform::ROT_180;
+        flags = ui::Transform::ROT_180;
         break;
     case DisplayState::eOrientation270:
-        flags = Transform::ROT_270;
+        flags = ui::Transform::ROT_270;
         break;
     default:
         return BAD_VALUE;
@@ -564,7 +563,7 @@
     const int w = mDisplayWidth;
     const int h = mDisplayHeight;
 
-    Transform R;
+    ui::Transform R;
     DisplayDevice::orientationToTransfrom(orientation, w, h, &R);
 
     if (!frame.isValid()) {
@@ -579,16 +578,16 @@
         // it's also invalid to have an empty viewport, so we handle that
         // case in the same way.
         viewport = Rect(w, h);
-        if (R.getOrientation() & Transform::ROT_90) {
+        if (R.getOrientation() & ui::Transform::ROT_90) {
             // viewport is always specified in the logical orientation
             // of the display (ie: post-rotation).
-            swap(viewport.right, viewport.bottom);
+            std::swap(viewport.right, viewport.bottom);
         }
     }
 
     dirtyRegion.set(getBounds());
 
-    Transform TL, TP, S;
+    ui::Transform TL, TP, S;
     float src_width  = viewport.width();
     float src_height = viewport.height();
     float dst_width  = frame.width();
@@ -622,7 +621,7 @@
 
     const uint8_t type = mGlobalTransform.getType();
     mNeedsFiltering = (!mGlobalTransform.preserveRects() ||
-            (type >= Transform::SCALE));
+            (type >= ui::Transform::SCALE));
 
     mScissor = mGlobalTransform.transform(viewport);
     if (mScissor.isEmpty()) {
@@ -634,16 +633,16 @@
         uint32_t transform = 0;
         switch (mOrientation) {
             case DisplayState::eOrientationDefault:
-                transform = Transform::ROT_0;
+                transform = ui::Transform::ROT_0;
                 break;
             case DisplayState::eOrientation90:
-                transform = Transform::ROT_90;
+                transform = ui::Transform::ROT_90;
                 break;
             case DisplayState::eOrientation180:
-                transform = Transform::ROT_180;
+                transform = ui::Transform::ROT_180;
                 break;
             case DisplayState::eOrientation270:
-                transform = Transform::ROT_270;
+                transform = ui::Transform::ROT_270;
                 break;
         }
         sPrimaryDisplayOrientation = transform;
@@ -657,7 +656,7 @@
 }
 
 void DisplayDevice::dump(String8& result) const {
-    const Transform& tr(mGlobalTransform);
+    const ui::Transform& tr(mGlobalTransform);
     ANativeWindow* const window = mNativeWindow.get();
     result.appendFormat("+ DisplayDevice: %s\n", mDisplayName.c_str());
     result.appendFormat("   type=%x, ID=%d, layerStack=%u, (%4dx%4d), ANativeWindow=%p "
diff --git a/services/surfaceflinger/DisplayDevice.h b/services/surfaceflinger/DisplayDevice.h
index f440d29..bcb2976 100644
--- a/services/surfaceflinger/DisplayDevice.h
+++ b/services/surfaceflinger/DisplayDevice.h
@@ -17,19 +17,20 @@
 #ifndef ANDROID_DISPLAY_DEVICE_H
 #define ANDROID_DISPLAY_DEVICE_H
 
-#include "Transform.h"
-
 #include <stdlib.h>
+
+#include <memory>
+#include <string>
 #include <unordered_map>
 
-#include <math/mat4.h>
-
 #include <binder/IBinder.h>
-#include <gui/ISurfaceComposer.h>
 #include <hardware/hwcomposer_defs.h>
+#include <gui/ISurfaceComposer.h>
+#include <math/mat4.h>
 #include <ui/GraphicTypes.h>
 #include <ui/HdrCapabilities.h>
 #include <ui/Region.h>
+#include <ui/Transform.h>
 #include <utils/RefBase.h>
 #include <utils/Mutex.h>
 #include <utils/String8.h>
@@ -38,9 +39,6 @@
 #include "RenderArea.h"
 #include "RenderEngine/Surface.h"
 
-#include <memory>
-#include <string>
-
 struct ANativeWindow;
 
 namespace android {
@@ -126,7 +124,7 @@
     int                     getOrientation() const { return mOrientation; }
     uint32_t                getOrientationTransform() const;
     static uint32_t         getPrimaryDisplayOrientationTransform();
-    const Transform&        getTransform() const { return mGlobalTransform; }
+    const ui::Transform&   getTransform() const { return mGlobalTransform; }
     const Rect              getViewport() const { return mViewport; }
     const Rect              getFrame() const { return mFrame; }
     const Rect&             getScissor() const { return mScissor; }
@@ -254,7 +252,7 @@
      * Transaction state
      */
     static status_t orientationToTransfrom(int orientation,
-            int w, int h, Transform* tr);
+                                           int w, int h, ui::Transform* tr);
 
     // The identifier of the active layer stack for this display. Several displays
     // can use the same layer stack: A z-ordered group of layers (sometimes called
@@ -269,7 +267,7 @@
     Rect mFrame;
     // pre-computed scissor to apply to the display
     Rect mScissor;
-    Transform mGlobalTransform;
+    ui::Transform mGlobalTransform;
     bool mNeedsFiltering;
     // Current power mode
     int mPowerMode;
@@ -344,7 +342,7 @@
           : RenderArea(reqHeight, reqWidth, CaptureFill::OPAQUE, rotation), mDevice(device),
                               mSourceCrop(sourceCrop) {}
 
-    const Transform& getTransform() const override { return mDevice->getTransform(); }
+    const ui::Transform& getTransform() const override { return mDevice->getTransform(); }
     Rect getBounds() const override { return mDevice->getBounds(); }
     int getHeight() const override { return mDevice->getHeight(); }
     int getWidth() const override { return mDevice->getWidth(); }
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index ee9ee78..f7f3fac 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -50,7 +50,6 @@
 #include "LayerRejecter.h"
 #include "MonitoredProducer.h"
 #include "SurfaceFlinger.h"
-#include "clz.h"
 
 #include "DisplayHardware/HWComposer.h"
 
@@ -132,22 +131,7 @@
     CompositorTiming compositorTiming;
     flinger->getCompositorTiming(&compositorTiming);
     mFrameEventHistory.initializeCompositorTiming(compositorTiming);
-}
-
-void Layer::onFirstRef() NO_THREAD_SAFETY_ANALYSIS {
-    if (!isCreatedFromMainThread()) {
-        // Grab the SF state lock during this since it's the only way to safely access HWC
-        mFlinger->mStateLock.lock();
-    }
-
-    const auto& hwc = mFlinger->getHwComposer();
-    const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
-    nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
-    mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
-
-    if (!isCreatedFromMainThread()) {
-        mFlinger->mStateLock.unlock();
-    }
+    mFrameTracker.setDisplayRefreshPeriod(compositorTiming.interval);
 }
 
 Layer::~Layer() {
@@ -230,7 +214,10 @@
 bool Layer::createHwcLayer(HWComposer* hwc, int32_t displayId) {
     LOG_ALWAYS_FATAL_IF(getBE().mHwcLayers.count(displayId) != 0,
                         "Already have a layer for display %d", displayId);
-    HWC2::Layer* layer = hwc->createLayer(displayId);
+    auto layer = std::shared_ptr<HWC2::Layer>(
+            hwc->createLayer(displayId),
+            [hwc, displayId](HWC2::Layer* layer) {
+               hwc->destroyLayer(displayId, layer); });
     if (!layer) {
         return false;
     }
@@ -249,11 +236,8 @@
     auto& hwcInfo = getBE().mHwcLayers[displayId];
     LOG_ALWAYS_FATAL_IF(hwcInfo.layer == nullptr, "Attempt to destroy null layer");
     LOG_ALWAYS_FATAL_IF(hwcInfo.hwc == nullptr, "Missing HWComposer");
-    hwcInfo.hwc->destroyLayer(displayId, hwcInfo.layer);
-    // The layer destroyed listener should have cleared the entry from
-    // mHwcLayers. Verify that.
-    LOG_ALWAYS_FATAL_IF(getBE().mHwcLayers.count(displayId) != 0,
-                        "Stale layer entry in getBE().mHwcLayers");
+    hwcInfo.layer = nullptr;
+
     return true;
 }
 
@@ -311,7 +295,7 @@
         win.intersect(crop, &win);
     }
 
-    Transform t = getTransform();
+    ui::Transform t = getTransform();
     win = t.transform(win);
 
     Rect finalCrop = getFinalCrop(s);
@@ -365,7 +349,7 @@
         parentBounds = p->computeBounds(Region());
     }
 
-    Transform t = s.active_legacy.transform;
+    ui::Transform t = s.active_legacy.transform;
 
     if (p != nullptr || !s.finalCrop_legacy.isEmpty()) {
         floatWin = t.transform(floatWin);
@@ -399,7 +383,7 @@
         activeCrop.intersect(crop, &activeCrop);
     }
 
-    Transform t = getTransform();
+    ui::Transform t = getTransform();
     activeCrop = t.transform(activeCrop);
     if (!activeCrop.intersect(display->getViewport(), &activeCrop)) {
         activeCrop.clear();
@@ -430,7 +414,7 @@
 
     // Screen space to make reduction to parent crop clearer.
     Rect activeCrop = computeInitialCrop(display);
-    Transform t = getTransform();
+    ui::Transform t = getTransform();
     // Back to layer space to work with the content crop.
     activeCrop = t.inverse().transform(activeCrop);
 
@@ -462,7 +446,8 @@
             invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_FLIP_H;
         }
         // and apply to the current transform
-        invTransform = (Transform(invTransformOrient) * Transform(invTransform)).getOrientation();
+        invTransform = (ui::Transform(invTransformOrient) *
+                        ui::Transform(invTransform)).getOrientation();
     }
 
     int winWidth = getActiveWidth(s);
@@ -535,7 +520,7 @@
     // apply the layer's transform, followed by the display's global transform
     // here we're guaranteed that the layer's transform preserves rects
     Region activeTransparentRegion(getActiveTransparentRegion(s));
-    Transform t = getTransform();
+    ui::Transform t = getTransform();
     Rect activeCrop = getCrop(s);
     if (!activeCrop.isEmpty()) {
         activeCrop = t.transform(activeCrop);
@@ -573,7 +558,7 @@
     if (!frame.intersect(display->getViewport(), &frame)) {
         frame.clear();
     }
-    const Transform& tr = display->getTransform();
+    const ui::Transform& tr = display->getTransform();
     Rect transformedFrame = tr.transform(frame);
     error = hwcLayer->setDisplayFrame(transformedFrame);
     if (error != HWC2::Error::None) {
@@ -629,8 +614,8 @@
      * (NOTE: the matrices are multiplied in reverse order)
      */
 
-    const Transform bufferOrientation(mCurrentTransform);
-    Transform transform(tr * t * bufferOrientation);
+    const ui::Transform bufferOrientation(mCurrentTransform);
+    ui::Transform transform(tr * t * bufferOrientation);
 
     if (getTransformToDisplayInverse()) {
         /*
@@ -649,12 +634,12 @@
          * computation so it's enough to just omit it in the composition.
          * See comment in onDraw with ref to b/36727915 for why.
          */
-        transform = Transform(invTransform) * tr * bufferOrientation;
+        transform = ui::Transform(invTransform) * tr * bufferOrientation;
     }
 
     // this gives us only the "orientation" component of the transform
     const uint32_t orientation = transform.getOrientation();
-    if (orientation & Transform::ROT_INVALID) {
+    if (orientation & ui::Transform::ROT_INVALID) {
         // we can only handle simple transformation
         hwcInfo.forceClientComposition = true;
     } else {
@@ -716,7 +701,8 @@
     auto position = displayTransform.transform(frame);
 
     auto error =
-            getBE().mHwcLayers[displayId].layer->setCursorPosition(position.left, position.top);
+            (getBE().mHwcLayers[displayId].layer)->setCursorPosition(
+                    position.left, position.top);
     ALOGE_IF(error != HWC2::Error::None,
              "[%s] Failed to set cursor position "
              "to (%d, %d): %s (%d)",
@@ -759,13 +745,13 @@
     }
     auto& hwcInfo = getBE().mHwcLayers[displayId];
     auto& hwcLayer = hwcInfo.layer;
-    ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(), to_string(type).c_str(),
+    ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", (hwcLayer)->getId(), to_string(type).c_str(),
           static_cast<int>(callIntoHwc));
     if (hwcInfo.compositionType != type) {
         ALOGV("    actually setting");
         hwcInfo.compositionType = type;
         if (callIntoHwc) {
-            auto error = hwcLayer->setCompositionType(type);
+            auto error = (hwcLayer)->setCompositionType(type);
             ALOGE_IF(error != HWC2::Error::None,
                      "[%s] Failed to set "
                      "composition type %s: %s (%d)",
@@ -846,7 +832,7 @@
 void Layer::computeGeometry(const RenderArea& renderArea, Mesh& mesh,
                             bool useIdentityTransform) const {
     const Layer::State& s(getDrawingState());
-    const Transform renderAreaTransform(renderArea.getTransform());
+    const ui::Transform renderAreaTransform(renderArea.getTransform());
     const uint32_t height = renderArea.getHeight();
     FloatRect win = computeBounds();
 
@@ -855,7 +841,7 @@
     vec2 rb = vec2(win.right, win.bottom);
     vec2 rt = vec2(win.right, win.top);
 
-    Transform layerTransform = getTransform();
+    ui::Transform layerTransform = getTransform();
     if (!useIdentityTransform) {
         lt = layerTransform.transform(lt);
         lb = layerTransform.transform(lb);
@@ -1119,7 +1105,7 @@
 
         // we may use linear filtering, if the matrix scales us
         const uint8_t type = getActiveTransform(c).getType();
-        mNeedsFiltering = (!getActiveTransform(c).preserveRects() || (type >= Transform::SCALE));
+        mNeedsFiltering = (!getActiveTransform(c).preserveRects() || type >= ui::Transform::SCALE);
     }
 
     // If the layer is hidden, signal and clear out all local sync points so
@@ -1294,7 +1280,7 @@
 
 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix,
         bool allowNonRectPreservingTransforms) {
-    Transform t;
+    ui::Transform t;
     t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
 
     if (!allowNonRectPreservingTransforms && !t.preserveRects()) {
@@ -1433,9 +1419,9 @@
         // The transform hint is used to improve performance, but we can
         // only have a single transform hint, it cannot
         // apply to all displays.
-        const Transform& planeTransform = display->getTransform();
+        const ui::Transform& planeTransform = display->getTransform();
         orientation = planeTransform.getOrientation();
-        if (orientation & Transform::ROT_INVALID) {
+        if (orientation & ui::Transform::ROT_INVALID) {
             orientation = 0;
         }
     }
@@ -1900,8 +1886,8 @@
     traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
 }
 
-Transform Layer::getTransform() const {
-    Transform t;
+ui::Transform Layer::getTransform() const {
+    ui::Transform t;
     const auto& p = mDrawingParent.promote();
     if (p != nullptr) {
         t = p->getTransform();
@@ -1923,7 +1909,7 @@
             }
             float sx = p->getActiveWidth(p->getDrawingState()) / static_cast<float>(bufferWidth);
             float sy = p->getActiveHeight(p->getDrawingState()) / static_cast<float>(bufferHeight);
-            Transform extraParentScaling;
+            ui::Transform extraParentScaling;
             extraParentScaling.set(sx, 0, 0, sy);
             t = t * extraParentScaling;
         }
@@ -1957,8 +1943,8 @@
     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
     const State& state = useDrawing ? mDrawingState : mCurrentState;
 
-    Transform requestedTransform = state.active_legacy.transform;
-    Transform transform = getTransform();
+    ui::Transform requestedTransform = state.active_legacy.transform;
+    ui::Transform transform = getTransform();
 
     layerInfo->set_id(sequence);
     layerInfo->set_name(getName().c_str());
@@ -2026,7 +2012,7 @@
     auto buffer = getBE().compositionInfo.mBuffer;
     if (buffer != nullptr) {
         LayerProtoHelper::writeToProto(buffer, layerInfo->mutable_active_buffer());
-        LayerProtoHelper::writeToProto(Transform(mCurrentTransform),
+        LayerProtoHelper::writeToProto(ui::Transform(mCurrentTransform),
                                        layerInfo->mutable_buffer_transform());
     }
 
diff --git a/services/surfaceflinger/Layer.h b/services/surfaceflinger/Layer.h
index a48cdff..6ebd668 100644
--- a/services/surfaceflinger/Layer.h
+++ b/services/surfaceflinger/Layer.h
@@ -28,10 +28,11 @@
 #include <ui/GraphicBuffer.h>
 #include <ui/PixelFormat.h>
 #include <ui/Region.h>
+#include <ui/Transform.h>
 
+#include <gui/BufferQueue.h>
 #include <gui/ISurfaceComposerClient.h>
 #include <gui/LayerState.h>
-#include <gui/BufferQueue.h>
 
 #include <list>
 #include <cstdint>
@@ -43,7 +44,6 @@
 #include "MonitoredProducer.h"
 #include "SurfaceFlinger.h"
 #include "TimeStats/TimeStats.h"
-#include "Transform.h"
 
 #include <layerproto/LayerProtoHeader.h>
 #include "DisplayHardware/HWComposer.h"
@@ -101,7 +101,7 @@
     struct Geometry {
         uint32_t w;
         uint32_t h;
-        Transform transform;
+        ui::Transform transform;
 
         inline bool operator==(const Geometry& rhs) const {
             return (w == rhs.w && h == rhs.h) && (transform.tx() == rhs.transform.tx()) &&
@@ -345,7 +345,7 @@
     virtual Geometry getActiveGeometry(const Layer::State& s) const { return s.active_legacy; }
     virtual uint32_t getActiveWidth(const Layer::State& s) const { return s.active_legacy.w; }
     virtual uint32_t getActiveHeight(const Layer::State& s) const { return s.active_legacy.h; }
-    virtual Transform getActiveTransform(const Layer::State& s) const {
+    virtual ui::Transform getActiveTransform(const Layer::State& s) const {
         return s.active_legacy.transform;
     }
     virtual Region getActiveTransparentRegion(const Layer::State& s) const {
@@ -510,7 +510,7 @@
         if (getBE().mHwcLayers.count(displayId) == 0) {
             return nullptr;
         }
-        return getBE().mHwcLayers[displayId].layer;
+        return getBE().mHwcLayers[displayId].layer.get();
     }
 
     // -----------------------------------------------------------------------
@@ -545,7 +545,7 @@
 
     virtual bool getTransformToDisplayInverse() const { return false; }
 
-    Transform getTransform() const;
+    ui::Transform getTransform() const;
 
     // Returns the Alpha of the Surface, accounting for the Alpha
     // of parent Surfaces in the hierarchy (alpha's will be multiplied
@@ -604,8 +604,6 @@
               : mFlinger(flinger), mLayer(layer) {}
     };
 
-    virtual void onFirstRef();
-
     friend class impl::SurfaceInterceptor;
 
     void commitTransaction(const State& stateToCommit);
diff --git a/services/surfaceflinger/LayerBE.cpp b/services/surfaceflinger/LayerBE.cpp
index 51b615b..b936b3f 100644
--- a/services/surfaceflinger/LayerBE.cpp
+++ b/services/surfaceflinger/LayerBE.cpp
@@ -26,16 +26,23 @@
 LayerBE::LayerBE(Layer* layer, std::string layerName)
       : mLayer(layer),
         mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2) {
-    compositionInfo.layer = this;
+    compositionInfo.layer = std::make_shared<LayerBE>(*this);
     compositionInfo.layerName = layerName;
 }
 
+LayerBE::LayerBE(const LayerBE& layer)
+      : mLayer(layer.mLayer),
+        mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2) {
+    compositionInfo.layer = layer.compositionInfo.layer;
+    compositionInfo.layerName = layer.mLayer->getName().string();
+}
+
 void LayerBE::onLayerDisplayed(const sp<Fence>& releaseFence) {
     mLayer->onLayerDisplayed(releaseFence);
 }
 
 void CompositionInfo::dumpHwc(const char* tag) const {
-    ALOGV("[%s]\thwcLayer=%p", tag, hwc.hwcLayer);
+    ALOGV("[%s]\thwcLayer=%p", tag, hwc.hwcLayer.get());
     ALOGV("[%s]\tfence=%p", tag, hwc.fence.get());
     ALOGV("[%s]\ttransform=%d", tag, hwc.transform);
     ALOGV("[%s]\tz=%d", tag, hwc.z);
diff --git a/services/surfaceflinger/LayerBE.h b/services/surfaceflinger/LayerBE.h
index b5aceba..3055621 100644
--- a/services/surfaceflinger/LayerBE.h
+++ b/services/surfaceflinger/LayerBE.h
@@ -37,9 +37,9 @@
     HWC2::Composition compositionType;
     sp<GraphicBuffer> mBuffer = nullptr;
     int mBufferSlot = BufferQueue::INVALID_BUFFER_SLOT;
-    LayerBE* layer = nullptr;
+    std::shared_ptr<LayerBE> layer;
     struct {
-        HWC2::Layer* hwcLayer;
+        std::shared_ptr<HWC2::Layer> hwcLayer;
         sp<Fence> fence;
         HWC2::BlendMode blendMode = HWC2::BlendMode::Invalid;
         Rect displayFrame;
@@ -54,6 +54,7 @@
         sp<NativeHandle> sidebandStream;
         ui::Dataspace dataspace;
         hwc_color_t color;
+        bool clearClientTarget = false;
     } hwc;
     struct {
         Mesh* mesh;
@@ -83,6 +84,7 @@
     friend class SurfaceFlinger;
 
     LayerBE(Layer* layer, std::string layerName);
+    explicit LayerBE(const LayerBE& layer);
 
     void onLayerDisplayed(const sp<Fence>& releaseFence);
     Mesh& getMesh() { return mMesh; }
@@ -103,7 +105,7 @@
                 transform(HWC2::Transform::None) {}
 
         HWComposer* hwc;
-        HWC2::Layer* layer;
+        std::shared_ptr<HWC2::Layer> layer;
         bool forceClientComposition;
         HWC2::Composition compositionType;
         bool clearClientTarget;
diff --git a/services/surfaceflinger/LayerProtoHelper.cpp b/services/surfaceflinger/LayerProtoHelper.cpp
index cc39550..3289e8f 100644
--- a/services/surfaceflinger/LayerProtoHelper.cpp
+++ b/services/surfaceflinger/LayerProtoHelper.cpp
@@ -51,7 +51,8 @@
     colorProto->set_a(color.a);
 }
 
-void LayerProtoHelper::writeToProto(const Transform& transform, TransformProto* transformProto) {
+void LayerProtoHelper::writeToProto(const ui::Transform& transform,
+                                    TransformProto* transformProto) {
     transformProto->set_dsdx(transform[0][0]);
     transformProto->set_dtdx(transform[0][1]);
     transformProto->set_dsdy(transform[1][0]);
diff --git a/services/surfaceflinger/LayerProtoHelper.h b/services/surfaceflinger/LayerProtoHelper.h
index 860da63..6df5aea 100644
--- a/services/surfaceflinger/LayerProtoHelper.h
+++ b/services/surfaceflinger/LayerProtoHelper.h
@@ -16,13 +16,11 @@
 
 #include <layerproto/LayerProtoHeader.h>
 
+#include <math/vec4.h>
 #include <ui/GraphicBuffer.h>
 #include <ui/Rect.h>
 #include <ui/Region.h>
-
-#include <Transform.h>
-
-#include <math/vec4.h>
+#include <ui/Transform.h>
 
 namespace android {
 namespace surfaceflinger {
@@ -32,7 +30,7 @@
     static void writeToProto(const FloatRect& rect, FloatRectProto* rectProto);
     static void writeToProto(const Region& region, RegionProto* regionProto);
     static void writeToProto(const half4 color, ColorProto* colorProto);
-    static void writeToProto(const Transform& transform, TransformProto* transformProto);
+    static void writeToProto(const ui::Transform& transform, TransformProto* transformProto);
     static void writeToProto(const sp<GraphicBuffer>& buffer, ActiveBufferProto* activeBufferProto);
 };
 
diff --git a/services/surfaceflinger/LayerRejecter.cpp b/services/surfaceflinger/LayerRejecter.cpp
index 70558d4..136cdc0 100644
--- a/services/surfaceflinger/LayerRejecter.cpp
+++ b/services/surfaceflinger/LayerRejecter.cpp
@@ -19,8 +19,6 @@
 #include <gui/BufferItem.h>
 #include <system/window.h>
 
-#include "clz.h"
-
 #define DEBUG_RESIZE 0
 
 namespace android {
@@ -52,14 +50,14 @@
 
     // check that we received a buffer of the right size
     // (Take the buffer's orientation into account)
-    if (item.mTransform & Transform::ROT_90) {
-        swap(bufWidth, bufHeight);
+    if (item.mTransform & ui::Transform::ROT_90) {
+        std::swap(bufWidth, bufHeight);
     }
 
     if (mTransformToDisplayInverse) {
         uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
-        if (invTransform & Transform::ROT_90) {
-            swap(bufWidth, bufHeight);
+        if (invTransform & ui::Transform::ROT_90) {
+            std::swap(bufWidth, bufHeight);
         }
     }
 
diff --git a/services/surfaceflinger/RenderArea.cpp b/services/surfaceflinger/RenderArea.cpp
index 1a8edf3..7f69ce4 100644
--- a/services/surfaceflinger/RenderArea.cpp
+++ b/services/surfaceflinger/RenderArea.cpp
@@ -4,6 +4,27 @@
 
 namespace android {
 
+ui::Transform::orientation_flags fromRotation(ISurfaceComposer::Rotation rotation) {
+    switch (rotation) {
+        case ISurfaceComposer::eRotateNone:
+            return ui::Transform::ROT_0;
+        case ISurfaceComposer::eRotate90:
+            return ui::Transform::ROT_90;
+        case ISurfaceComposer::eRotate180:
+            return ui::Transform::ROT_180;
+        case ISurfaceComposer::eRotate270:
+            return ui::Transform::ROT_270;
+    }
+    ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
+    return ui::Transform::ROT_0;
+}
+
+RenderArea::RenderArea(uint32_t reqHeight, uint32_t reqWidth, CaptureFill captureFill,
+                       ISurfaceComposer::Rotation rotation)
+      : mReqHeight(reqHeight), mReqWidth(reqWidth), mCaptureFill(captureFill) {
+    mRotationFlags = fromRotation(rotation);
+}
+
 float RenderArea::getCaptureFillValue(CaptureFill captureFill) {
     switch(captureFill) {
         case CaptureFill::CLEAR:
@@ -23,7 +44,7 @@
     uint32_t width = getWidth();
     uint32_t height = getHeight();
 
-    if (mRotationFlags & Transform::ROT_90) {
+    if (mRotationFlags & ui::Transform::ROT_90) {
         std::swap(width, height);
     }
 
diff --git a/services/surfaceflinger/RenderArea.h b/services/surfaceflinger/RenderArea.h
index 96e4b5f..e38f462 100644
--- a/services/surfaceflinger/RenderArea.h
+++ b/services/surfaceflinger/RenderArea.h
@@ -1,8 +1,8 @@
 #pragma once
 
+#include <gui/ISurfaceComposer.h>
 #include <ui/GraphicTypes.h>
-
-#include "Transform.h"
+#include <ui/Transform.h>
 
 #include <functional>
 
@@ -16,14 +16,11 @@
     static float getCaptureFillValue(CaptureFill captureFill);
 
     RenderArea(uint32_t reqHeight, uint32_t reqWidth, CaptureFill captureFill,
-               ISurfaceComposer::Rotation rotation = ISurfaceComposer::eRotateNone)
-          : mReqHeight(reqHeight), mReqWidth(reqWidth), mCaptureFill(captureFill) {
-        mRotationFlags = Transform::fromRotation(rotation);
-    }
+               ISurfaceComposer::Rotation rotation = ISurfaceComposer::eRotateNone);
 
     virtual ~RenderArea() = default;
 
-    virtual const Transform& getTransform() const = 0;
+    virtual const ui::Transform& getTransform() const = 0;
     virtual Rect getBounds() const = 0;
     virtual int getHeight() const = 0;
     virtual int getWidth() const = 0;
@@ -35,7 +32,7 @@
 
     int getReqHeight() const { return mReqHeight; };
     int getReqWidth() const { return mReqWidth; };
-    Transform::orientation_flags getRotationFlags() const { return mRotationFlags; };
+    ui::Transform::orientation_flags getRotationFlags() const { return mRotationFlags; };
     status_t updateDimensions(int displayRotation);
 
     CaptureFill getCaptureFill() const { return mCaptureFill; };
@@ -43,7 +40,7 @@
 private:
     uint32_t mReqHeight;
     uint32_t mReqWidth;
-    Transform::orientation_flags mRotationFlags;
+    ui::Transform::orientation_flags mRotationFlags;
     CaptureFill mCaptureFill;
 };
 
diff --git a/services/surfaceflinger/RenderEngine/Description.cpp b/services/surfaceflinger/RenderEngine/Description.cpp
index c218e4d..d4a2bb4 100644
--- a/services/surfaceflinger/RenderEngine/Description.cpp
+++ b/services/surfaceflinger/RenderEngine/Description.cpp
@@ -19,9 +19,6 @@
 
 #include <utils/TypeHelpers.h>
 
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
-
 #include "Description.h"
 
 namespace android {
diff --git a/services/surfaceflinger/RenderEngine/GLES20RenderEngine.cpp b/services/surfaceflinger/RenderEngine/GLES20RenderEngine.cpp
index 4860f3c..2186594 100644
--- a/services/surfaceflinger/RenderEngine/GLES20RenderEngine.cpp
+++ b/services/surfaceflinger/RenderEngine/GLES20RenderEngine.cpp
@@ -167,7 +167,7 @@
 
 void GLES20RenderEngine::setViewportAndProjection(size_t vpw, size_t vph, Rect sourceCrop,
                                                   size_t hwh, bool yswap,
-                                                  Transform::orientation_flags rotation) {
+                                                  ui::Transform::orientation_flags rotation) {
     int32_t l = sourceCrop.left;
     int32_t r = sourceCrop.right;
 
@@ -185,15 +185,15 @@
     // Apply custom rotation to the projection.
     float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
     switch (rotation) {
-        case Transform::ROT_0:
+        case ui::Transform::ROT_0:
             break;
-        case Transform::ROT_90:
+        case ui::Transform::ROT_90:
             m = mat4::rotate(rot90InRadians, vec3(0, 0, 1)) * m;
             break;
-        case Transform::ROT_180:
+        case ui::Transform::ROT_180:
             m = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1)) * m;
             break;
-        case Transform::ROT_270:
+        case ui::Transform::ROT_270:
             m = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1)) * m;
             break;
         default:
diff --git a/services/surfaceflinger/RenderEngine/GLES20RenderEngine.h b/services/surfaceflinger/RenderEngine/GLES20RenderEngine.h
index cc8eb1d..f682225 100644
--- a/services/surfaceflinger/RenderEngine/GLES20RenderEngine.h
+++ b/services/surfaceflinger/RenderEngine/GLES20RenderEngine.h
@@ -21,7 +21,6 @@
 #include <sys/types.h>
 
 #include <GLES2/gl2.h>
-#include <Transform.h>
 
 #include "Description.h"
 #include "ProgramCache.h"
@@ -67,7 +66,7 @@
 protected:
     virtual void dump(String8& result);
     virtual void setViewportAndProjection(size_t vpw, size_t vph, Rect sourceCrop, size_t hwh,
-                                          bool yswap, Transform::orientation_flags rotation);
+                                          bool yswap, ui::Transform::orientation_flags rotation);
     virtual void setupLayerBlending(bool premultipliedAlpha, bool opaque, bool disableTexture,
                                     const half4& color) override;
 
diff --git a/services/surfaceflinger/RenderEngine/RenderEngine.h b/services/surfaceflinger/RenderEngine/RenderEngine.h
index d2b218e..2ed2cc7 100644
--- a/services/surfaceflinger/RenderEngine/RenderEngine.h
+++ b/services/surfaceflinger/RenderEngine/RenderEngine.h
@@ -24,9 +24,10 @@
 
 #include <EGL/egl.h>
 #include <EGL/eglext.h>
-#include <Transform.h>
 #include <android-base/unique_fd.h>
 #include <math/mat4.h>
+#include <ui/GraphicTypes.h>
+#include <ui/Transform.h>
 
 #define EGL_NO_CONFIG ((EGLConfig)0)
 
@@ -105,7 +106,7 @@
     // set-up
     virtual void checkErrors() const;
     virtual void setViewportAndProjection(size_t vpw, size_t vph, Rect sourceCrop, size_t hwh,
-                                          bool yswap, Transform::orientation_flags rotation) = 0;
+                                          bool yswap, ui::Transform::orientation_flags rotation) = 0;
     virtual void setupLayerBlending(bool premultipliedAlpha, bool opaque, bool disableTexture,
                                     const half4& color) = 0;
     virtual void setupLayerTexturing(const Texture& texture) = 0;
diff --git a/services/surfaceflinger/RenderEngine/Surface.cpp b/services/surfaceflinger/RenderEngine/Surface.cpp
index 0d20f1f..3bf42fb 100644
--- a/services/surfaceflinger/RenderEngine/Surface.cpp
+++ b/services/surfaceflinger/RenderEngine/Surface.cpp
@@ -19,6 +19,7 @@
 #include "RenderEngine.h"
 
 #include <log/log.h>
+#include <ui/PixelFormat.h>
 
 namespace android {
 namespace RE {
diff --git a/services/surfaceflinger/Scheduler/DispSyncSource.cpp b/services/surfaceflinger/Scheduler/DispSyncSource.cpp
new file mode 100644
index 0000000..697d634
--- /dev/null
+++ b/services/surfaceflinger/Scheduler/DispSyncSource.cpp
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define ATRACE_TAG ATRACE_TAG_GRAPHICS
+
+#include "DispSyncSource.h"
+
+#include <android-base/stringprintf.h>
+#include <utils/Trace.h>
+#include <mutex>
+
+#include "DispSync.h"
+#include "EventThread.h"
+
+namespace android {
+
+DispSyncSource::DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
+                               const char* name)
+      : mName(name),
+        mTraceVsync(traceVsync),
+        mVsyncOnLabel(base::StringPrintf("VsyncOn-%s", name)),
+        mVsyncEventLabel(base::StringPrintf("VSYNC-%s", name)),
+        mDispSync(dispSync),
+        mPhaseOffset(phaseOffset) {}
+
+void DispSyncSource::setVSyncEnabled(bool enable) {
+    std::lock_guard lock(mVsyncMutex);
+    if (enable) {
+        status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
+                                                   static_cast<DispSync::Callback*>(this));
+        if (err != NO_ERROR) {
+            ALOGE("error registering vsync callback: %s (%d)", strerror(-err), err);
+        }
+        // ATRACE_INT(mVsyncOnLabel.c_str(), 1);
+    } else {
+        status_t err = mDispSync->removeEventListener(static_cast<DispSync::Callback*>(this));
+        if (err != NO_ERROR) {
+            ALOGE("error unregistering vsync callback: %s (%d)", strerror(-err), err);
+        }
+        // ATRACE_INT(mVsyncOnLabel.c_str(), 0);
+    }
+    mEnabled = enable;
+}
+
+void DispSyncSource::setCallback(VSyncSource::Callback* callback) {
+    std::lock_guard lock(mCallbackMutex);
+    mCallback = callback;
+}
+
+void DispSyncSource::setPhaseOffset(nsecs_t phaseOffset) {
+    std::lock_guard lock(mVsyncMutex);
+
+    // Normalize phaseOffset to [0, period)
+    auto period = mDispSync->getPeriod();
+    phaseOffset %= period;
+    if (phaseOffset < 0) {
+        // If we're here, then phaseOffset is in (-period, 0). After this
+        // operation, it will be in (0, period)
+        phaseOffset += period;
+    }
+    mPhaseOffset = phaseOffset;
+
+    // If we're not enabled, we don't need to mess with the listeners
+    if (!mEnabled) {
+        return;
+    }
+
+    status_t err =
+            mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this), mPhaseOffset);
+    if (err != NO_ERROR) {
+        ALOGE("error changing vsync offset: %s (%d)", strerror(-err), err);
+    }
+}
+
+void DispSyncSource::onDispSyncEvent(nsecs_t when) {
+    VSyncSource::Callback* callback;
+    {
+        std::lock_guard lock(mCallbackMutex);
+        callback = mCallback;
+
+        if (mTraceVsync) {
+            mValue = (mValue + 1) % 2;
+            ATRACE_INT(mVsyncEventLabel.c_str(), mValue);
+        }
+    }
+
+    if (callback != nullptr) {
+        callback->onVSyncEvent(when);
+    }
+}
+
+} // namespace android
\ No newline at end of file
diff --git a/services/surfaceflinger/Scheduler/DispSyncSource.h b/services/surfaceflinger/Scheduler/DispSyncSource.h
new file mode 100644
index 0000000..0fd84a2
--- /dev/null
+++ b/services/surfaceflinger/Scheduler/DispSyncSource.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <mutex>
+#include <string>
+
+#include "DispSync.h"
+#include "EventThread.h"
+
+namespace android {
+
+class DispSyncSource final : public VSyncSource, private DispSync::Callback {
+public:
+    DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync, const char* name);
+
+    ~DispSyncSource() override = default;
+
+    // The following methods are implementation of VSyncSource.
+    void setVSyncEnabled(bool enable) override;
+    void setCallback(VSyncSource::Callback* callback) override;
+    void setPhaseOffset(nsecs_t phaseOffset) override;
+
+private:
+    // The following method is the implementation of the DispSync::Callback.
+    virtual void onDispSyncEvent(nsecs_t when);
+
+    const char* const mName;
+    int mValue = 0;
+
+    const bool mTraceVsync;
+    const std::string mVsyncOnLabel;
+    const std::string mVsyncEventLabel;
+
+    DispSync* mDispSync;
+
+    std::mutex mCallbackMutex;
+    VSyncSource::Callback* mCallback GUARDED_BY(mCallbackMutex) = nullptr;
+
+    std::mutex mVsyncMutex;
+    nsecs_t mPhaseOffset GUARDED_BY(mVsyncMutex);
+    bool mEnabled GUARDED_BY(mVsyncMutex) = false;
+};
+
+} // namespace android
\ No newline at end of file
diff --git a/services/surfaceflinger/Scheduler/InjectVSyncSource.h b/services/surfaceflinger/Scheduler/InjectVSyncSource.h
new file mode 100644
index 0000000..a0e1447
--- /dev/null
+++ b/services/surfaceflinger/Scheduler/InjectVSyncSource.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <mutex>
+
+#include "EventThread.h"
+
+namespace android {
+
+/**
+ * VSync signals used during SurfaceFlinger trace playback (traces we captured
+ * with SurfaceInterceptor).
+ */
+class InjectVSyncSource final : public VSyncSource {
+public:
+    ~InjectVSyncSource() override = default;
+
+    void setCallback(VSyncSource::Callback* callback) override {
+        std::lock_guard<std::mutex> lock(mCallbackMutex);
+        mCallback = callback;
+    }
+
+    void onInjectSyncEvent(nsecs_t when) {
+        std::lock_guard<std::mutex> lock(mCallbackMutex);
+        if (mCallback) {
+            mCallback->onVSyncEvent(when);
+        }
+    }
+
+    void setVSyncEnabled(bool) override {}
+    void setPhaseOffset(nsecs_t) override {}
+
+private:
+    std::mutex mCallbackMutex;
+    VSyncSource::Callback* mCallback GUARDED_BY(mCallbackMutex) = nullptr;
+};
+
+} // namespace android
\ No newline at end of file
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 6b222d5..f5c0b74 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -75,7 +75,6 @@
 #include "LayerVector.h"
 #include "MonitoredProducer.h"
 #include "SurfaceFlinger.h"
-#include "clz.h"
 
 #include "DisplayHardware/ComposerHal.h"
 #include "DisplayHardware/DisplayIdentification.h"
@@ -85,8 +84,10 @@
 #include "Effects/Daltonizer.h"
 #include "RenderEngine/RenderEngine.h"
 #include "Scheduler/DispSync.h"
+#include "Scheduler/DispSyncSource.h"
 #include "Scheduler/EventControlThread.h"
 #include "Scheduler/EventThread.h"
+#include "Scheduler/InjectVSyncSource.h"
 
 #include <cutils/compiler.h>
 
@@ -265,6 +266,7 @@
         mForceFullDamage(false),
         mPrimaryHWVsyncEnabled(false),
         mHWVsyncAvailable(false),
+        mRefreshStartTime(0),
         mHasPoweredOff(false),
         mNumLayers(0),
         mVrFlingerRequestsDisplay(false),
@@ -564,137 +566,6 @@
     postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
 }
 
-class DispSyncSource final : public VSyncSource, private DispSync::Callback {
-public:
-    DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
-        const char* name) :
-            mName(name),
-            mValue(0),
-            mTraceVsync(traceVsync),
-            mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
-            mVsyncEventLabel(String8::format("VSYNC-%s", name)),
-            mDispSync(dispSync),
-            mCallbackMutex(),
-            mVsyncMutex(),
-            mPhaseOffset(phaseOffset),
-            mEnabled(false) {}
-
-    ~DispSyncSource() override = default;
-
-    void setVSyncEnabled(bool enable) override {
-        Mutex::Autolock lock(mVsyncMutex);
-        if (enable) {
-            status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
-                    static_cast<DispSync::Callback*>(this));
-            if (err != NO_ERROR) {
-                ALOGE("error registering vsync callback: %s (%d)",
-                        strerror(-err), err);
-            }
-            //ATRACE_INT(mVsyncOnLabel.string(), 1);
-        } else {
-            status_t err = mDispSync->removeEventListener(
-                    static_cast<DispSync::Callback*>(this));
-            if (err != NO_ERROR) {
-                ALOGE("error unregistering vsync callback: %s (%d)",
-                        strerror(-err), err);
-            }
-            //ATRACE_INT(mVsyncOnLabel.string(), 0);
-        }
-        mEnabled = enable;
-    }
-
-    void setCallback(VSyncSource::Callback* callback) override{
-        Mutex::Autolock lock(mCallbackMutex);
-        mCallback = callback;
-    }
-
-    void setPhaseOffset(nsecs_t phaseOffset) override {
-        Mutex::Autolock lock(mVsyncMutex);
-
-        // Normalize phaseOffset to [0, period)
-        auto period = mDispSync->getPeriod();
-        phaseOffset %= period;
-        if (phaseOffset < 0) {
-            // If we're here, then phaseOffset is in (-period, 0). After this
-            // operation, it will be in (0, period)
-            phaseOffset += period;
-        }
-        mPhaseOffset = phaseOffset;
-
-        // If we're not enabled, we don't need to mess with the listeners
-        if (!mEnabled) {
-            return;
-        }
-
-        status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
-                mPhaseOffset);
-        if (err != NO_ERROR) {
-            ALOGE("error changing vsync offset: %s (%d)",
-                    strerror(-err), err);
-        }
-    }
-
-private:
-    virtual void onDispSyncEvent(nsecs_t when) {
-        VSyncSource::Callback* callback;
-        {
-            Mutex::Autolock lock(mCallbackMutex);
-            callback = mCallback;
-
-            if (mTraceVsync) {
-                mValue = (mValue + 1) % 2;
-                ATRACE_INT(mVsyncEventLabel.string(), mValue);
-            }
-        }
-
-        if (callback != nullptr) {
-            callback->onVSyncEvent(when);
-        }
-    }
-
-    const char* const mName;
-
-    int mValue;
-
-    const bool mTraceVsync;
-    const String8 mVsyncOnLabel;
-    const String8 mVsyncEventLabel;
-
-    DispSync* mDispSync;
-
-    Mutex mCallbackMutex; // Protects the following
-    VSyncSource::Callback* mCallback = nullptr;
-
-    Mutex mVsyncMutex; // Protects the following
-    nsecs_t mPhaseOffset;
-    bool mEnabled;
-};
-
-class InjectVSyncSource final : public VSyncSource {
-public:
-    InjectVSyncSource() = default;
-    ~InjectVSyncSource() override = default;
-
-    void setCallback(VSyncSource::Callback* callback) override {
-        std::lock_guard<std::mutex> lock(mCallbackMutex);
-        mCallback = callback;
-    }
-
-    void onInjectSyncEvent(nsecs_t when) {
-        std::lock_guard<std::mutex> lock(mCallbackMutex);
-        if (mCallback) {
-            mCallback->onVSyncEvent(when);
-        }
-    }
-
-    void setVSyncEnabled(bool) override {}
-    void setPhaseOffset(nsecs_t) override {}
-
-private:
-    std::mutex mCallbackMutex; // Protects the following
-    VSyncSource::Callback* mCallback = nullptr;
-};
-
 // Do not call property_set on main thread which will be blocked by init
 // Use StartPropertySetThread instead.
 void SurfaceFlinger::init() {
@@ -1583,16 +1454,16 @@
 
     mRefreshPending = false;
 
-    nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
-
-    preComposition(refreshStartTime);
+    preComposition();
     rebuildLayerStacks();
-    setUpHWComposer();
+    calculateWorkingSet();
+    beginFrame();
+    prepareFrame();
     doDebugFlashRegions();
     doTracing("handleRefresh");
     logLayerStats();
     doComposition();
-    postComposition(refreshStartTime);
+    postComposition();
 
     mHadClientComposition = false;
     for (const auto& [token, display] : mDisplays) {
@@ -1604,6 +1475,84 @@
     mLayersWithQueuedFrames.clear();
 }
 
+void SurfaceFlinger::calculateWorkingSet() {
+    ATRACE_CALL();
+    ALOGV(__FUNCTION__);
+
+    // build the h/w work list
+    if (CC_UNLIKELY(mGeometryInvalid)) {
+        mGeometryInvalid = false;
+        for (const auto& [token, display] : mDisplays) {
+            const auto displayId = display->getId();
+            if (displayId >= 0) {
+                const Vector<sp<Layer>>& currentLayers(
+                        display->getVisibleLayersSortedByZ());
+                for (size_t i = 0; i < currentLayers.size(); i++) {
+                    const auto& layer = currentLayers[i];
+
+                    if (!layer->hasHwcLayer(displayId)) {
+                        if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
+                            layer->forceClientComposition(displayId);
+                            continue;
+                        }
+                    }
+
+                    layer->setGeometry(display, i);
+                    if (mDebugDisableHWC || mDebugRegion) {
+                        layer->forceClientComposition(displayId);
+                    }
+                }
+            }
+        }
+    }
+
+    // Set the per-frame data
+    for (const auto& [token, display] : mDisplays) {
+        const auto displayId = display->getId();
+        if (displayId < 0) {
+            continue;
+        }
+
+        if (mDrawingState.colorMatrixChanged) {
+            display->setColorTransform(mDrawingState.colorMatrix);
+            status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
+            ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
+                    "display %d: %d", displayId, result);
+        }
+        for (auto& layer : display->getVisibleLayersSortedByZ()) {
+            if (layer->isHdrY410()) {
+                layer->forceClientComposition(displayId);
+            } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
+                        layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
+                    !display->hasHDR10Support()) {
+                layer->forceClientComposition(displayId);
+            } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
+                        layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
+                    !display->hasHLGSupport()) {
+                layer->forceClientComposition(displayId);
+            }
+
+            if (layer->getForceClientComposition(displayId)) {
+                ALOGV("[%s] Requesting Client composition", layer->getName().string());
+                layer->setCompositionType(displayId, HWC2::Composition::Client);
+                continue;
+            }
+
+            layer->setPerFrameData(display);
+        }
+
+        if (hasWideColorDisplay) {
+            ColorMode  colorMode;
+            Dataspace dataSpace;
+            RenderIntent renderIntent;
+            pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
+            setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
+        }
+    }
+
+    mDrawingState.colorMatrixChanged = false;
+}
+
 void SurfaceFlinger::doDebugFlashRegions()
 {
     // is debugging enabled
@@ -1668,14 +1617,16 @@
     }
 }
 
-void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
+void SurfaceFlinger::preComposition()
 {
     ATRACE_CALL();
     ALOGV("preComposition");
 
+    mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
+
     bool needExtraInvalidate = false;
     mDrawingState.traverseInZOrder([&](Layer* layer) {
-        if (layer->onPreComposition(refreshStartTime)) {
+        if (layer->onPreComposition(mRefreshStartTime)) {
             needExtraInvalidate = true;
         }
     });
@@ -1744,7 +1695,7 @@
     getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
 }
 
-void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
+void SurfaceFlinger::postComposition()
 {
     ATRACE_CALL();
     ALOGV("postComposition");
@@ -1777,11 +1728,11 @@
     nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
     nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
 
-    // We use the refreshStartTime which might be sampled a little later than
+    // We use the mRefreshStartTime which might be sampled a little later than
     // when we started doing work for this frame, but that should be okay
     // since updateCompositorTiming has snapping logic.
     updateCompositorTiming(
-        vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
+        vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
     CompositorTiming compositorTiming;
     {
         std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
@@ -1879,7 +1830,7 @@
             Region dirtyRegion;
             Vector<sp<Layer>> layersSortedByZ;
             Vector<sp<Layer>> layersNeedingFences;
-            const Transform& tr = display->getTransform();
+            const ui::Transform& tr = display->getTransform();
             const Rect bounds = display->getBounds();
             if (display->isPoweredOn()) {
                 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
@@ -2003,10 +1954,8 @@
     display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
 }
 
-void SurfaceFlinger::setUpHWComposer() {
-    ATRACE_CALL();
-    ALOGV("setUpHWComposer");
-
+void SurfaceFlinger::beginFrame()
+{
     for (const auto& [token, display] : mDisplays) {
         bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
         bool empty = display->getVisibleLayersSortedByZ().size() == 0;
@@ -2032,78 +1981,10 @@
             display->lastCompositionHadVisibleLayers = !empty;
         }
     }
+}
 
-    // build the h/w work list
-    if (CC_UNLIKELY(mGeometryInvalid)) {
-        mGeometryInvalid = false;
-        for (const auto& [token, display] : mDisplays) {
-            const auto displayId = display->getId();
-            if (displayId >= 0) {
-                const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
-                for (size_t i = 0; i < currentLayers.size(); i++) {
-                    const auto& layer = currentLayers[i];
-                    if (!layer->hasHwcLayer(displayId)) {
-                        if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
-                            layer->forceClientComposition(displayId);
-                            continue;
-                        }
-                    }
-
-                    layer->setGeometry(display, i);
-                    if (mDebugDisableHWC || mDebugRegion) {
-                        layer->forceClientComposition(displayId);
-                    }
-                }
-            }
-        }
-    }
-
-    // Set the per-frame data
-    for (const auto& [token, display] : mDisplays) {
-        const auto displayId = display->getId();
-        if (displayId < 0) {
-            continue;
-        }
-
-        if (mDrawingState.colorMatrixChanged) {
-            display->setColorTransform(mDrawingState.colorMatrix);
-            status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
-            ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
-                     displayId, result);
-        }
-        for (auto& layer : display->getVisibleLayersSortedByZ()) {
-            if (layer->isHdrY410()) {
-                layer->forceClientComposition(displayId);
-            } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
-                        layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
-                    !display->hasHDR10Support()) {
-                layer->forceClientComposition(displayId);
-            } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
-                        layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
-                    !display->hasHLGSupport()) {
-                layer->forceClientComposition(displayId);
-            }
-
-            if (layer->getForceClientComposition(displayId)) {
-                ALOGV("[%s] Requesting Client composition", layer->getName().string());
-                layer->setCompositionType(displayId, HWC2::Composition::Client);
-                continue;
-            }
-
-            layer->setPerFrameData(display);
-        }
-
-        if (hasWideColorDisplay) {
-            ColorMode colorMode;
-            Dataspace dataSpace;
-            RenderIntent renderIntent;
-            pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
-            setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
-        }
-    }
-
-    mDrawingState.colorMatrixChanged = false;
-
+void SurfaceFlinger::prepareFrame()
+{
     for (const auto& [token, display] : mDisplays) {
         if (!display->isPoweredOn()) {
             continue;
@@ -2328,7 +2209,9 @@
                     getHwComposer().getRenderIntents(displayId, colorMode);
             hwcColorModes.emplace(colorMode, renderIntents);
         }
+    }
 
+    if (displayId >= 0) {
         getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
         supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
     }
@@ -2765,7 +2648,7 @@
             const bool translucent = !layer->isOpaque(s);
             Rect bounds(layer->computeScreenBounds());
             visibleRegion.set(bounds);
-            Transform tr = layer->getTransform();
+            ui::Transform tr = layer->getTransform();
             if (!visibleRegion.isEmpty()) {
                 // Remove the transparent area from the visible region
                 if (translucent) {
@@ -2782,7 +2665,7 @@
                 // compute the opaque region
                 const int32_t layerOrientation = tr.getOrientation();
                 if (layer->getAlpha() == 1.0f && !translucent &&
-                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
+                        ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
                     // the opaque region is the layer's footprint
                     opaqueRegion = visibleRegion;
                 }
@@ -3045,7 +2928,7 @@
      */
 
     ALOGV("Rendering client layers");
-    const Transform& displayTransform = display->getTransform();
+    const ui::Transform& displayTransform = display->getTransform();
     bool firstLayer = true;
     for (auto& layer : display->getVisibleLayersSortedByZ()) {
         const Region clip(bounds.intersect(
@@ -4379,7 +4262,7 @@
                 appEarlyOffset,
                 sfEarlyOffset,
                 appEarlyGlOffset,
-                sfEarlyOffset,
+                sfEarlyGlOffset,
                 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
     }
     result.append("\n");
@@ -4937,7 +4820,7 @@
                 mCrop(crop),
                 mFlinger(flinger),
                 mChildrenOnly(childrenOnly) {}
-        const Transform& getTransform() const override { return mTransform; }
+        const ui::Transform& getTransform() const override { return mTransform; }
         Rect getBounds() const override {
             const Layer::State& layerState(mLayer->getDrawingState());
             return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
@@ -4989,7 +4872,7 @@
         // In the "childrenOnly" case we reparent the children to a screenshot
         // layer which has no properties set and which does not draw.
         sp<ContainerLayer> screenshotParentLayer;
-        Transform mTransform;
+        ui::Transform mTransform;
 
         SurfaceFlinger* mFlinger;
         const bool mChildrenOnly;
@@ -5143,17 +5026,17 @@
         sourceCrop.setLeftTop(Point(0, 0));
         sourceCrop.setRightBottom(Point(raWidth, raHeight));
     } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
-        Transform tr;
+        ui::Transform tr;
         uint32_t flags = 0x00;
         switch (mPrimaryDisplayOrientation) {
             case DisplayState::eOrientation90:
-                flags = Transform::ROT_90;
+                flags = ui::Transform::ROT_90;
                 break;
             case DisplayState::eOrientation180:
-                flags = Transform::ROT_180;
+                flags = ui::Transform::ROT_180;
                 break;
             case DisplayState::eOrientation270:
-                flags = Transform::ROT_270;
+                flags = ui::Transform::ROT_270;
                 break;
         }
         tr.set(flags, raWidth, raHeight);
@@ -5181,7 +5064,7 @@
     // make sure to clear all GL error flags
     engine.checkErrors();
 
-    Transform::orientation_flags rotation = renderArea.getRotationFlags();
+    ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
     if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
         // convert hw orientation into flag presentation
         // here inverse transform needed
@@ -5189,26 +5072,26 @@
         uint8_t hw_flip_hv = 0x00;
         switch (mPrimaryDisplayOrientation) {
             case DisplayState::eOrientation90:
-                hw_rot_90 = Transform::ROT_90;
-                hw_flip_hv = Transform::ROT_180;
+                hw_rot_90 = ui::Transform::ROT_90;
+                hw_flip_hv = ui::Transform::ROT_180;
                 break;
             case DisplayState::eOrientation180:
-                hw_flip_hv = Transform::ROT_180;
+                hw_flip_hv = ui::Transform::ROT_180;
                 break;
             case DisplayState::eOrientation270:
-                hw_rot_90  = Transform::ROT_90;
+                hw_rot_90  = ui::Transform::ROT_90;
                 break;
         }
 
         // transform flags operation
         // 1) flip H V if both have ROT_90 flag
         // 2) XOR these flags
-        uint8_t rotation_rot_90  = rotation & Transform::ROT_90;
-        uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
+        uint8_t rotation_rot_90  = rotation & ui::Transform::ROT_90;
+        uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
         if (rotation_rot_90 & hw_rot_90) {
-            rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
+            rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
         }
-        rotation = static_cast<Transform::orientation_flags>
+        rotation = static_cast<ui::Transform::orientation_flags>
                    ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
     }
 
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index 5ceea3a..f5d8eb4 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -648,8 +648,8 @@
     void computeVisibleRegions(const sp<const DisplayDevice>& display, Region& dirtyRegion,
                                Region& opaqueRegion);
 
-    void preComposition(nsecs_t refreshStartTime);
-    void postComposition(nsecs_t refreshStartTime);
+    void preComposition();
+    void postComposition();
     void updateCompositorTiming(
             nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
             std::shared_ptr<FenceTime>& presentFenceTime);
@@ -667,7 +667,18 @@
     void pickColorMode(const sp<DisplayDevice>& display, ui::ColorMode* outMode,
                        ui::Dataspace* outDataSpace, ui::RenderIntent* outRenderIntent) const;
 
-    void setUpHWComposer();
+    void calculateWorkingSet();
+    /*
+     * beginFrame - This function handles any pre-frame processing that needs to be
+     * prior to any CompositionInfo handling and is not dependent on data in
+     * CompositionInfo
+     */
+    void beginFrame();
+    /* prepareFrame - This function will call into the DisplayDevice to prepare a
+     * frame after CompositionInfo has been programmed.   This provides a mechanism
+     * to prepare the hardware composer
+     */
+    void prepareFrame();
     void doComposition();
     void doDebugFlashRegions();
     void doTracing(const char* where);
@@ -863,6 +874,7 @@
     Mutex mHWVsyncLock;
     bool mPrimaryHWVsyncEnabled;
     bool mHWVsyncAvailable;
+    nsecs_t mRefreshStartTime;
 
     std::atomic<bool> mRefreshPending{false};
 
diff --git a/services/surfaceflinger/Transform.h b/services/surfaceflinger/Transform.h
deleted file mode 100644
index b11d057..0000000
--- a/services/surfaceflinger/Transform.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2007 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.
- */
-
-#ifndef ANDROID_TRANSFORM_H
-#define ANDROID_TRANSFORM_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <ui/Point.h>
-#include <ui/Rect.h>
-#include <math/vec2.h>
-#include <math/vec3.h>
-
-#include <gui/ISurfaceComposer.h>
-
-#include <hardware/hardware.h>
-
-namespace android {
-
-class Region;
-
-// ---------------------------------------------------------------------------
-
-class Transform
-{
-public:
-                    Transform();
-                    Transform(const Transform&  other);
-           explicit Transform(uint32_t orientation);
-                    ~Transform();
-
-            enum orientation_flags {
-                ROT_0   = 0x00000000,
-                FLIP_H  = HAL_TRANSFORM_FLIP_H,
-                FLIP_V  = HAL_TRANSFORM_FLIP_V,
-                ROT_90  = HAL_TRANSFORM_ROT_90,
-                ROT_180 = FLIP_H|FLIP_V,
-                ROT_270 = ROT_180|ROT_90,
-                ROT_INVALID = 0x80
-            };
-
-            static orientation_flags fromRotation(ISurfaceComposer::Rotation rotation);
-
-            enum type_mask {
-                IDENTITY            = 0,
-                TRANSLATE           = 0x1,
-                ROTATE              = 0x2,
-                SCALE               = 0x4,
-                UNKNOWN             = 0x8
-            };
-
-            // query the transform
-            bool        preserveRects() const;
-            uint32_t    getType() const;
-            uint32_t    getOrientation() const;
-
-            const vec3& operator [] (size_t i) const;  // returns column i
-            float   tx() const;
-            float   ty() const;
-
-            // modify the transform
-            void        reset();
-            void        set(float tx, float ty);
-            void        set(float a, float b, float c, float d);
-            status_t    set(uint32_t flags, float w, float h);
-
-            // transform data
-            Rect    makeBounds(int w, int h) const;
-            vec2    transform(int x, int y) const;
-            Region  transform(const Region& reg) const;
-            Rect    transform(const Rect& bounds,
-                    bool roundOutwards = false) const;
-            FloatRect transform(const FloatRect& bounds) const;
-            Transform operator * (const Transform& rhs) const;
-            // assumes the last row is < 0 , 0 , 1 >
-            vec2 transform(const vec2& v) const;
-            vec3 transform(const vec3& v) const;
-
-            Transform inverse() const;
-
-            // for debugging
-            void dump(const char* name) const;
-
-private:
-    struct mat33 {
-        vec3 v[3];
-        inline const vec3& operator [] (int i) const { return v[i]; }
-        inline vec3& operator [] (int i) { return v[i]; }
-    };
-
-    enum { UNKNOWN_TYPE = 0x80000000 };
-
-    uint32_t type() const;
-    static bool absIsOne(float f);
-    static bool isZero(float f);
-
-    mat33               mMatrix;
-    mutable uint32_t    mType;
-};
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-
-#endif /* ANDROID_TRANSFORM_H */
diff --git a/services/surfaceflinger/clz.h b/services/surfaceflinger/clz.h
deleted file mode 100644
index a4c5262..0000000
--- a/services/surfaceflinger/clz.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2007 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.
- */
-
-#ifndef ANDROID_SURFACE_FLINGER_CLZ_H
-
-#include <stdint.h>
-
-namespace android {
-
-int inline clz(int32_t x) {
-    return __builtin_clz(x);
-}
-
-template <typename T>
-static inline T min(T a, T b) {
-    return a<b ? a : b;
-}
-template <typename T>
-static inline T min(T a, T b, T c) {
-    return min(a, min(b, c));
-}
-template <typename T>
-static inline T min(T a, T b, T c, T d) {
-    return min(a, b, min(c, d));
-}
-
-template <typename T>
-static inline T max(T a, T b) {
-    return a>b ? a : b;
-}
-template <typename T>
-static inline T max(T a, T b, T c) {
-    return max(a, max(b, c));
-}
-template <typename T>
-static inline T max(T a, T b, T c, T d) {
-    return max(a, b, max(c, d));
-}
-
-template <typename T>
-static inline
-void swap(T& a, T& b) {
-    T t(a);
-    a = b;
-    b = t;
-}
-
-
-}; // namespace android
-
-#endif /* ANDROID_SURFACE_FLINGER_CLZ_H */
diff --git a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
index 508875d..b4aec36 100644
--- a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
+++ b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
@@ -657,7 +657,8 @@
 using SimpleHwcVirtualDisplayVariant = HwcVirtualDisplayVariant<1024, 768, Secure::TRUE>;
 using HwcVirtualDisplayCase =
         Case<SimpleHwcVirtualDisplayVariant, WideColorSupportNotConfiguredVariant,
-             NonHwcDisplayHdrSupportVariant, NonHwcPerFrameMetadataSupportVariant>;
+             HdrNotSupportedVariant<SimpleHwcVirtualDisplayVariant>, 
+             NoPerFrameMetadataSupportVariant<SimpleHwcVirtualDisplayVariant>>;
 using WideColorP3ColorimetricDisplayCase =
         Case<PrimaryDisplayVariant, WideColorP3ColorimetricSupportedVariant<PrimaryDisplayVariant>,
              HdrNotSupportedVariant<PrimaryDisplayVariant>,
diff --git a/services/surfaceflinger/tests/unittests/mock/RenderEngine/MockRenderEngine.h b/services/surfaceflinger/tests/unittests/mock/RenderEngine/MockRenderEngine.h
index 7814d32..36f74b6 100644
--- a/services/surfaceflinger/tests/unittests/mock/RenderEngine/MockRenderEngine.h
+++ b/services/surfaceflinger/tests/unittests/mock/RenderEngine/MockRenderEngine.h
@@ -56,7 +56,7 @@
     MOCK_METHOD5(readPixels, void(size_t, size_t, size_t, size_t, uint32_t*));
     MOCK_CONST_METHOD0(checkErrors, void());
     MOCK_METHOD6(setViewportAndProjection,
-                 void(size_t, size_t, Rect, size_t, bool, Transform::orientation_flags));
+                 void(size_t, size_t, Rect, size_t, bool, ui::Transform::orientation_flags));
     MOCK_METHOD4(setupLayerBlending, void(bool, bool, bool, const half4&));
     MOCK_METHOD1(setupLayerTexturing, void(const Texture&));
     MOCK_METHOD0(setupLayerBlackedOut, void());