Merge "BLASTBufferQueue: Don't use mNextTransaction on Binder thread." into rvc-dev
diff --git a/cmds/installd/InstalldNativeService.cpp b/cmds/installd/InstalldNativeService.cpp
index ae44d38..7d1c1ad 100644
--- a/cmds/installd/InstalldNativeService.cpp
+++ b/cmds/installd/InstalldNativeService.cpp
@@ -420,6 +420,32 @@
     return true;
 }
 
+binder::Status InstalldNativeService::createAppDataBatched(
+        const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& uuids,
+        const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& packageNames,
+        int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
+        const std::vector<std::string>& seInfos, const std::vector<int32_t>& targetSdkVersions,
+        int64_t* _aidl_return) {
+    ENFORCE_UID(AID_SYSTEM);
+    std::lock_guard<std::recursive_mutex> lock(mLock);
+
+    ATRACE_BEGIN("createAppDataBatched");
+    binder::Status ret;
+    for (size_t i = 0; i < uuids->size(); i++) {
+        if (!packageNames->at(i)) {
+            continue;
+        }
+        ret = createAppData(uuids->at(i), *packageNames->at(i), userId, flags, appIds[i],
+                seInfos[i], targetSdkVersions[i], _aidl_return);
+        if (!ret.isOk()) {
+            ATRACE_END();
+            return ret;
+        }
+    }
+    ATRACE_END();
+    return ok();
+}
+
 binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
         const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
         const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
diff --git a/cmds/installd/InstalldNativeService.h b/cmds/installd/InstalldNativeService.h
index eb151ca..8e7d98b 100644
--- a/cmds/installd/InstalldNativeService.h
+++ b/cmds/installd/InstalldNativeService.h
@@ -44,7 +44,12 @@
             int32_t userSerial, int32_t flags);
     binder::Status destroyUserData(const std::unique_ptr<std::string>& uuid, int32_t userId,
             int32_t flags);
-
+    binder::Status createAppDataBatched(
+            const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& uuids,
+            const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& packageNames,
+            int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
+            const std::vector<std::string>& seInfos, const std::vector<int32_t>& targetSdkVersions,
+            int64_t* _aidl_return);
     binder::Status createAppData(const std::unique_ptr<std::string>& uuid,
             const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
             const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return);
diff --git a/cmds/installd/binder/android/os/IInstalld.aidl b/cmds/installd/binder/android/os/IInstalld.aidl
index 5e5af73..eeda6c5 100644
--- a/cmds/installd/binder/android/os/IInstalld.aidl
+++ b/cmds/installd/binder/android/os/IInstalld.aidl
@@ -23,6 +23,9 @@
 
     long createAppData(@nullable @utf8InCpp String uuid, in @utf8InCpp String packageName,
             int userId, int flags, int appId, in @utf8InCpp String seInfo, int targetSdkVersion);
+    long createAppDataBatched(in @nullable @utf8InCpp String[] uuids,
+        in @nullable @utf8InCpp String[] packageNames, in int userId, int flags, in int[] appIds,
+        in @utf8InCpp String[] seInfos, in int[] targetSdkVersions);
     void restoreconAppData(@nullable @utf8InCpp String uuid, @utf8InCpp String packageName,
             int userId, int flags, int appId, @utf8InCpp String seInfo);
     void migrateAppData(@nullable @utf8InCpp String uuid, @utf8InCpp String packageName,
diff --git a/cmds/installd/dexopt.cpp b/cmds/installd/dexopt.cpp
index 5ee6a9f..2944ac5 100644
--- a/cmds/installd/dexopt.cpp
+++ b/cmds/installd/dexopt.cpp
@@ -262,6 +262,17 @@
   return "";
 }
 
+static std::string MapPropertyToArgWithBackup(const std::string& property,
+                                              const std::string& backupProperty,
+                                              const std::string& format,
+                                              const std::string& default_value = "") {
+  std::string value = GetProperty(property, default_value);
+  if (!value.empty()) {
+    return StringPrintf(format.c_str(), value.c_str());
+  }
+  return MapPropertyToArg(backupProperty, format, default_value);
+}
+
 // Determines which binary we should use for execution (the debug or non-debug version).
 // e.g. dex2oatd vs dex2oat
 static const char* select_execution_binary(const char* binary, const char* debug_binary,
@@ -321,6 +332,7 @@
                const char* compiler_filter,
                bool debuggable,
                bool post_bootcomplete,
+               bool for_restore,
                bool background_job_compile,
                int profile_fd,
                const char* class_loader_context,
@@ -336,14 +348,24 @@
         std::string dex2oat_Xms_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xms", "-Xms%s");
         std::string dex2oat_Xmx_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xmx", "-Xmx%s");
 
-        const char* threads_property = post_bootcomplete
-                ? "dalvik.vm.dex2oat-threads"
-                : "dalvik.vm.boot-dex2oat-threads";
-        std::string dex2oat_threads_arg = MapPropertyToArg(threads_property, "-j%s");
-        const char* cpu_set_property = post_bootcomplete
-                ? "dalvik.vm.dex2oat-cpu-set"
-                : "dalvik.vm.boot-dex2oat-cpu-set";
-        std::string dex2oat_cpu_set_arg = MapPropertyToArg(cpu_set_property, "--cpu-set=%s");
+        std::string threads_format = "-j%s";
+        std::string dex2oat_threads_arg = post_bootcomplete
+                ? (for_restore
+                    ? MapPropertyToArgWithBackup(
+                            "dalvik.vm.restore-dex2oat-threads",
+                            "dalvik.vm.dex2oat-threads",
+                            threads_format)
+                    : MapPropertyToArg("dalvik.vm.dex2oat-threads", threads_format))
+                : MapPropertyToArg("dalvik.vm.boot-dex2oat-threads", threads_format);
+        std::string cpu_set_format = "--cpu-set=%s";
+        std::string dex2oat_cpu_set_arg = post_bootcomplete
+                ? (for_restore
+                    ? MapPropertyToArgWithBackup(
+                            "dalvik.vm.restore-dex2oat-cpu-set",
+                            "dalvik.vm.dex2oat-cpu-set",
+                            cpu_set_format)
+                    : MapPropertyToArg("dalvik.vm.dex2oat-cpu-set", cpu_set_format))
+                : MapPropertyToArg("dalvik.vm.boot-dex2oat-cpu-set", cpu_set_format);
 
         std::string bootclasspath;
         char* dex2oat_bootclasspath = getenv("DEX2OATBOOTCLASSPATH");
@@ -2075,6 +2097,7 @@
     bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
     bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
     bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
+    bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
 
     // Check if we're dealing with a secondary dex file and if we need to compile it.
     std::string oat_dir_str;
@@ -2191,6 +2214,7 @@
                       compiler_filter,
                       debuggable,
                       boot_complete,
+                      for_restore,
                       background_job_compile,
                       reference_profile_fd.get(),
                       class_loader_context,
diff --git a/cmds/installd/installd_constants.h b/cmds/installd/installd_constants.h
index c928631..b5ee481 100644
--- a/cmds/installd/installd_constants.h
+++ b/cmds/installd/installd_constants.h
@@ -55,6 +55,7 @@
 constexpr int DEXOPT_ENABLE_HIDDEN_API_CHECKS = 1 << 10;
 constexpr int DEXOPT_GENERATE_COMPACT_DEX = 1 << 11;
 constexpr int DEXOPT_GENERATE_APP_IMAGE = 1 << 12;
+constexpr int DEXOPT_FOR_RESTORE = 1 << 13; // TODO(b/135202722): remove
 
 /* all known values for dexopt flags */
 constexpr int DEXOPT_MASK =
@@ -69,7 +70,8 @@
     | DEXOPT_IDLE_BACKGROUND_JOB
     | DEXOPT_ENABLE_HIDDEN_API_CHECKS
     | DEXOPT_GENERATE_COMPACT_DEX
-    | DEXOPT_GENERATE_APP_IMAGE;
+    | DEXOPT_GENERATE_APP_IMAGE
+    | DEXOPT_FOR_RESTORE;
 
 // NOTE: keep in sync with StorageManager
 constexpr int FLAG_STORAGE_DE = 1 << 0;
diff --git a/cmds/installd/otapreopt.cpp b/cmds/installd/otapreopt.cpp
index d773790..18f8268 100644
--- a/cmds/installd/otapreopt.cpp
+++ b/cmds/installd/otapreopt.cpp
@@ -83,7 +83,7 @@
 static_assert(DEXOPT_GENERATE_COMPACT_DEX == 1 << 11, "DEXOPT_GENERATE_COMPACT_DEX unexpected");
 static_assert(DEXOPT_GENERATE_APP_IMAGE == 1 << 12, "DEXOPT_GENERATE_APP_IMAGE unexpected");
 
-static_assert(DEXOPT_MASK           == (0x1dfe | DEXOPT_IDLE_BACKGROUND_JOB),
+static_assert(DEXOPT_MASK           == (0x3dfe | DEXOPT_IDLE_BACKGROUND_JOB),
               "DEXOPT_MASK unexpected.");
 
 
diff --git a/cmds/installd/tests/installd_dexopt_test.cpp b/cmds/installd/tests/installd_dexopt_test.cpp
index 69fefa1..1435456 100644
--- a/cmds/installd/tests/installd_dexopt_test.cpp
+++ b/cmds/installd/tests/installd_dexopt_test.cpp
@@ -653,6 +653,15 @@
                         DEX2OAT_FROM_SCRATCH);
 }
 
+TEST_F(DexoptTest, DexoptPrimaryPublicRestore) {
+    LOG(INFO) << "DexoptPrimaryPublicRestore";
+    CompilePrimaryDexOk("verify",
+                        DEXOPT_FOR_RESTORE | DEXOPT_BOOTCOMPLETE | DEXOPT_PUBLIC,
+                        app_oat_dir_.c_str(),
+                        kTestAppGid,
+                        DEX2OAT_FROM_SCRATCH);
+}
+
 TEST_F(DexoptTest, DexoptPrimaryFailedInvalidFilter) {
     LOG(INFO) << "DexoptPrimaryFailedInvalidFilter";
     binder::Status status;
diff --git a/headers/media_plugin/media/openmax/OMX_IndexExt.h b/headers/media_plugin/media/openmax/OMX_IndexExt.h
index bbb3193..a427db7 100644
--- a/headers/media_plugin/media/openmax/OMX_IndexExt.h
+++ b/headers/media_plugin/media/openmax/OMX_IndexExt.h
@@ -89,6 +89,7 @@
     OMX_IndexParamVideoVp9,                         /**< reference: OMX_VIDEO_PARAM_VP9TYPE */
     OMX_IndexParamVideoAndroidVp9Encoder,           /**< reference: OMX_VIDEO_PARAM_ANDROID_VP9ENCODERTYPE */
     OMX_IndexParamVideoAndroidImageGrid,            /**< reference: OMX_VIDEO_PARAM_ANDROID_IMAGEGRIDTYPE */
+    OMX_IndexParamVideoAndroidRequiresSwRenderer,   /**< reference: OMX_PARAM_U32TYPE */
     OMX_IndexExtVideoEndUnused,
 
     /* Image & Video common configurations */
diff --git a/include/input/InputWindow.h b/include/input/InputWindow.h
index c44db51..a695a8f 100644
--- a/include/input/InputWindow.h
+++ b/include/input/InputWindow.h
@@ -123,17 +123,17 @@
     // input windows that have the same token.
     sp<IBinder> token;
     // This uniquely identifies the input window.
-    int32_t id = 0;
+    int32_t id = -1;
     std::string name;
-    int32_t layoutParamsFlags;
-    int32_t layoutParamsType;
-    nsecs_t dispatchingTimeout;
+    int32_t layoutParamsFlags = 0;
+    int32_t layoutParamsType = 0;
+    nsecs_t dispatchingTimeout = -1;
 
     /* These values are filled in by SurfaceFlinger. */
-    int32_t frameLeft;
-    int32_t frameTop;
-    int32_t frameRight;
-    int32_t frameBottom;
+    int32_t frameLeft = -1;
+    int32_t frameTop = -1;
+    int32_t frameRight = -1;
+    int32_t frameBottom = -1;
 
     /*
      * SurfaceFlinger consumes this value to shrink the computed frame. This is
@@ -145,7 +145,7 @@
 
     // A global scaling factor for all windows. Unlike windowScaleX/Y this results
     // in scaling of the TOUCH_MAJOR/TOUCH_MINOR axis.
-    float globalScaleFactor;
+    float globalScaleFactor = 1.0f;
 
     // Scaling factors applied to individual windows.
     float windowXScale = 1.0f;
@@ -156,18 +156,18 @@
      * to absolute coordinates by SurfaceFlinger once the frame is computed.
      */
     Region touchableRegion;
-    bool visible;
-    bool canReceiveKeys;
-    bool hasFocus;
-    bool hasWallpaper;
-    bool paused;
-    int32_t ownerPid;
-    int32_t ownerUid;
-    int32_t inputFeatures;
-    int32_t displayId;
+    bool visible = false;
+    bool canReceiveKeys = false;
+    bool hasFocus = false;
+    bool hasWallpaper = false;
+    bool paused = false;
+    int32_t ownerPid = -1;
+    int32_t ownerUid = -1;
+    int32_t inputFeatures = 0;
+    int32_t displayId = ADISPLAY_ID_NONE;
     int32_t portalToDisplayId = ADISPLAY_ID_NONE;
     InputApplicationInfo applicationInfo;
-    bool replaceTouchableRegionWithCrop;
+    bool replaceTouchableRegionWithCrop = false;
     wp<IBinder> touchableRegionCropHandle;
 
     void addTouchableRegion(const Rect& region);
@@ -213,7 +213,7 @@
     }
 
     inline std::string getName() const {
-        return mInfo.token ? mInfo.name : "<invalid>";
+        return !mInfo.name.empty() ? mInfo.name : "<invalid>";
     }
 
     inline nsecs_t getDispatchingTimeout(nsecs_t defaultValue) const {
diff --git a/libs/binder/Android.bp b/libs/binder/Android.bp
index e6cfeb4..7298282 100644
--- a/libs/binder/Android.bp
+++ b/libs/binder/Android.bp
@@ -170,6 +170,7 @@
 
 aidl_interface {
     name: "libbinder_aidl_test_stub",
+    unstable: true,
     local_include_dir: "aidl",
     srcs: [":libbinder_aidl"],
     vendor_available: true,
diff --git a/libs/binder/ndk/test/Android.bp b/libs/binder/ndk/test/Android.bp
index cb4b20f..5f5265c 100644
--- a/libs/binder/ndk/test/Android.bp
+++ b/libs/binder/ndk/test/Android.bp
@@ -92,6 +92,7 @@
 
 aidl_interface {
     name: "IBinderVendorDoubleLoadTest",
+    unstable: true,
     vendor: true,
     srcs: [
         "IBinderVendorDoubleLoadTest.aidl",
@@ -100,6 +101,7 @@
 
 aidl_interface {
     name: "IBinderNdkUnitTest",
+    unstable: true,
     srcs: [
         "IBinderNdkUnitTest.aidl",
         "IEmpty.aidl",
diff --git a/libs/binder/tests/Android.bp b/libs/binder/tests/Android.bp
index c7b7551..69fdd7c 100644
--- a/libs/binder/tests/Android.bp
+++ b/libs/binder/tests/Android.bp
@@ -137,6 +137,7 @@
 
 aidl_interface {
     name: "binderStabilityTestIface",
+    unstable: true,
     srcs: [
         "IBinderStabilityTest.aidl",
     ],
diff --git a/libs/binderthreadstate/Android.bp b/libs/binderthreadstate/Android.bp
index c186110..5eb509c 100644
--- a/libs/binderthreadstate/Android.bp
+++ b/libs/binderthreadstate/Android.bp
@@ -39,6 +39,7 @@
 
 aidl_interface {
     name: "binderthreadstateutilstest.aidl",
+    unstable: true,
     srcs: ["IAidlStuff.aidl"],
 }
 
diff --git a/libs/gui/tests/BLASTBufferQueue_test.cpp b/libs/gui/tests/BLASTBufferQueue_test.cpp
index a87ccd6..d929a59 100644
--- a/libs/gui/tests/BLASTBufferQueue_test.cpp
+++ b/libs/gui/tests/BLASTBufferQueue_test.cpp
@@ -722,5 +722,8 @@
     ASSERT_EQ(2, events->frameNumber);
     ASSERT_EQ(requestedPresentTimeB, events->requestedPresentTime);
     ASSERT_GE(events->postedTime, postedTimeB);
+
+    // wait for any callbacks that have not been received
+    adapter.waitForCallbacks();
 }
 } // namespace android
diff --git a/libs/input/InputWindow.cpp b/libs/input/InputWindow.cpp
index 03ca459..6e4c97d 100644
--- a/libs/input/InputWindow.cpp
+++ b/libs/input/InputWindow.cpp
@@ -65,7 +65,7 @@
 }
 
 status_t InputWindowInfo::write(Parcel& output) const {
-    if (token == nullptr) {
+    if (name.empty()) {
         output.writeInt32(0);
         return OK;
     }
@@ -110,12 +110,7 @@
         return ret;
     }
 
-    sp<IBinder> token = from.readStrongBinder();
-    if (token == nullptr) {
-        return ret;
-    }
-
-    ret.token = token;
+    ret.token = from.readStrongBinder();
     ret.id = from.readInt32();
     ret.name = from.readString8().c_str();
     ret.layoutParamsFlags = from.readInt32();
diff --git a/services/inputflinger/dispatcher/InputDispatcher.cpp b/services/inputflinger/dispatcher/InputDispatcher.cpp
index 4ec61b0..403e21d 100644
--- a/services/inputflinger/dispatcher/InputDispatcher.cpp
+++ b/services/inputflinger/dispatcher/InputDispatcher.cpp
@@ -3598,8 +3598,8 @@
             if (canReceiveInput && !noInputChannel) {
                 ALOGV("Window handle %s has no registered input channel",
                       handle->getName().c_str());
+                continue;
             }
-            continue;
         }
 
         if (info->displayId != displayId) {
diff --git a/services/sensorservice/SensorDevice.cpp b/services/sensorservice/SensorDevice.cpp
index 3b68e0e..aa6f1b8 100644
--- a/services/sensorservice/SensorDevice.cpp
+++ b/services/sensorservice/SensorDevice.cpp
@@ -143,6 +143,14 @@
                 for (size_t i=0 ; i < count; i++) {
                     sensor_t sensor;
                     convertToSensor(convertToOldSensorInfo(list[i]), &sensor);
+
+                    if (sensor.resolution == 0) {
+                        // Don't crash here or the device will go into a crashloop.
+                        ALOGE("%s must have a non-zero resolution", sensor.name);
+                        // For simple algos, map their resolution to 1 if it's not specified
+                        sensor.resolution = SensorDeviceUtils::defaultResolutionForType(sensor.type);
+                    }
+
                     // Sanity check and clamp power if it is 0 (or close)
                     if (sensor.power < minPowerMa) {
                         ALOGI("Reported power %f not deemed sane, clamping to %f",
@@ -508,7 +516,7 @@
                     const auto &events,
                     const auto &dynamicSensorsAdded) {
                     if (result == Result::OK) {
-                        convertToSensorEvents(convertToNewEvents(events),
+                        convertToSensorEventsAndQuantize(convertToNewEvents(events),
                                 convertToNewSensorInfos(dynamicSensorsAdded), buffer);
                         err = (ssize_t)events.size();
                     } else {
@@ -571,6 +579,8 @@
 
             for (size_t i = 0; i < eventsToRead; i++) {
                 convertToSensorEvent(mEventBuffer[i], &buffer[i]);
+                android::SensorDeviceUtils::quantizeSensorEventValues(&buffer[i],
+                        getResolutionForSensor(buffer[i].sensor));
             }
             eventsRead = eventsToRead;
         } else {
@@ -1077,7 +1087,7 @@
     }
 }
 
-void SensorDevice::convertToSensorEvents(
+void SensorDevice::convertToSensorEventsAndQuantize(
         const hidl_vec<Event> &src,
         const hidl_vec<SensorInfo> &dynamicSensorsAdded,
         sensors_event_t *dst) {
@@ -1088,9 +1098,26 @@
 
     for (size_t i = 0; i < src.size(); ++i) {
         V2_1::implementation::convertToSensorEvent(src[i], &dst[i]);
+        android::SensorDeviceUtils::quantizeSensorEventValues(&dst[i],
+                getResolutionForSensor(dst[i].sensor));
     }
 }
 
+float SensorDevice::getResolutionForSensor(int sensorHandle) {
+    for (size_t i = 0; i < mSensorList.size(); i++) {
+      if (sensorHandle == mSensorList[i].handle) {
+        return mSensorList[i].resolution;
+      }
+    }
+
+    auto it = mConnectedDynamicSensors.find(sensorHandle);
+    if (it != mConnectedDynamicSensors.end()) {
+      return it->second->resolution;
+    }
+
+    return 0;
+}
+
 void SensorDevice::handleHidlDeath(const std::string & detail) {
     if (!mSensors->supportsMessageQueues()) {
         // restart is the only option at present.
diff --git a/services/sensorservice/SensorDevice.h b/services/sensorservice/SensorDevice.h
index 24d03c6..04e6031 100644
--- a/services/sensorservice/SensorDevice.h
+++ b/services/sensorservice/SensorDevice.h
@@ -233,11 +233,13 @@
 
     void convertToSensorEvent(const Event &src, sensors_event_t *dst);
 
-    void convertToSensorEvents(
+    void convertToSensorEventsAndQuantize(
             const hardware::hidl_vec<Event> &src,
             const hardware::hidl_vec<SensorInfo> &dynamicSensorsAdded,
             sensors_event_t *dst);
 
+    float getResolutionForSensor(int sensorHandle);
+
     bool mIsDirectReportSupported;
 
     typedef hardware::MessageQueue<uint32_t, hardware::kSynchronizedReadWrite> WakeLockQueue;
diff --git a/services/sensorservice/SensorDeviceUtils.cpp b/services/sensorservice/SensorDeviceUtils.cpp
index dbafffe..6bf62e4 100644
--- a/services/sensorservice/SensorDeviceUtils.cpp
+++ b/services/sensorservice/SensorDeviceUtils.cpp
@@ -17,16 +17,112 @@
 #include "SensorDeviceUtils.h"
 
 #include <android/hardware/sensors/1.0/ISensors.h>
+#include <android/hardware/sensors/2.1/ISensors.h>
 #include <utils/Log.h>
 
 #include <chrono>
+#include <cmath>
 #include <thread>
 
 using ::android::hardware::Void;
+using SensorTypeV2_1 = android::hardware::sensors::V2_1::SensorType;
 using namespace android::hardware::sensors::V1_0;
 
 namespace android {
 namespace SensorDeviceUtils {
+namespace {
+
+inline void quantizeValue(float *value, double resolution) {
+    // Increase the value of the sensor's nominal resolution to ensure that
+    // sensor accuracy improvements, like runtime calibration, are not masked
+    // during requantization.
+    double incRes = 0.25 * resolution;
+    *value = round(static_cast<double>(*value) / incRes) * incRes;
+}
+
+}  // namespace
+
+void quantizeSensorEventValues(sensors_event_t *event, float resolution) {
+    LOG_FATAL_IF(resolution == 0, "Resolution must be specified for all sensors!");
+    if (resolution == 0) {
+        return;
+    }
+
+    size_t axes = 0;
+    switch ((SensorTypeV2_1)event->type) {
+        case SensorTypeV2_1::ACCELEROMETER:
+        case SensorTypeV2_1::MAGNETIC_FIELD:
+        case SensorTypeV2_1::ORIENTATION:
+        case SensorTypeV2_1::GYROSCOPE:
+        case SensorTypeV2_1::GRAVITY:
+        case SensorTypeV2_1::LINEAR_ACCELERATION:
+        case SensorTypeV2_1::MAGNETIC_FIELD_UNCALIBRATED:
+        case SensorTypeV2_1::GYROSCOPE_UNCALIBRATED:
+        case SensorTypeV2_1::ACCELEROMETER_UNCALIBRATED:
+            axes = 3;
+            break;
+        case SensorTypeV2_1::GAME_ROTATION_VECTOR:
+            axes = 4;
+            break;
+        case SensorTypeV2_1::ROTATION_VECTOR:
+        case SensorTypeV2_1::GEOMAGNETIC_ROTATION_VECTOR:
+            axes = 5;
+            break;
+        case SensorTypeV2_1::DEVICE_ORIENTATION:
+        case SensorTypeV2_1::LIGHT:
+        case SensorTypeV2_1::PRESSURE:
+        case SensorTypeV2_1::TEMPERATURE:
+        case SensorTypeV2_1::PROXIMITY:
+        case SensorTypeV2_1::RELATIVE_HUMIDITY:
+        case SensorTypeV2_1::AMBIENT_TEMPERATURE:
+        case SensorTypeV2_1::SIGNIFICANT_MOTION:
+        case SensorTypeV2_1::STEP_DETECTOR:
+        case SensorTypeV2_1::TILT_DETECTOR:
+        case SensorTypeV2_1::WAKE_GESTURE:
+        case SensorTypeV2_1::GLANCE_GESTURE:
+        case SensorTypeV2_1::PICK_UP_GESTURE:
+        case SensorTypeV2_1::WRIST_TILT_GESTURE:
+        case SensorTypeV2_1::STATIONARY_DETECT:
+        case SensorTypeV2_1::MOTION_DETECT:
+        case SensorTypeV2_1::HEART_BEAT:
+        case SensorTypeV2_1::LOW_LATENCY_OFFBODY_DETECT:
+        case SensorTypeV2_1::HINGE_ANGLE:
+            axes = 1;
+            break;
+        case SensorTypeV2_1::POSE_6DOF:
+            axes = 15;
+            break;
+        default:
+            // No other sensors have data that needs to be rounded.
+            break;
+    }
+
+    // sensor_event_t is a union so we're able to perform the same quanitization action for most
+    // sensors by only knowing the number of axes their output data has.
+    for (size_t i = 0; i < axes; i++) {
+        quantizeValue(&event->data[i], resolution);
+    }
+}
+
+float defaultResolutionForType(int type) {
+    switch ((SensorTypeV2_1)type) {
+        case SensorTypeV2_1::SIGNIFICANT_MOTION:
+        case SensorTypeV2_1::STEP_DETECTOR:
+        case SensorTypeV2_1::STEP_COUNTER:
+        case SensorTypeV2_1::TILT_DETECTOR:
+        case SensorTypeV2_1::WAKE_GESTURE:
+        case SensorTypeV2_1::GLANCE_GESTURE:
+        case SensorTypeV2_1::PICK_UP_GESTURE:
+        case SensorTypeV2_1::WRIST_TILT_GESTURE:
+        case SensorTypeV2_1::STATIONARY_DETECT:
+        case SensorTypeV2_1::MOTION_DETECT:
+            return 1.0f;
+        default:
+            // fall through and return 0 for all other types
+            break;
+    }
+    return 0.0f;
+}
 
 HidlServiceRegistrationWaiter::HidlServiceRegistrationWaiter() {
 }
diff --git a/services/sensorservice/SensorDeviceUtils.h b/services/sensorservice/SensorDeviceUtils.h
index e2eb606..b66542c 100644
--- a/services/sensorservice/SensorDeviceUtils.h
+++ b/services/sensorservice/SensorDeviceUtils.h
@@ -18,6 +18,7 @@
 #define ANDROID_SENSOR_DEVICE_UTIL
 
 #include <android/hidl/manager/1.0/IServiceNotification.h>
+#include <hardware/sensors.h>
 
 #include <condition_variable>
 #include <thread>
@@ -29,6 +30,12 @@
 namespace android {
 namespace SensorDeviceUtils {
 
+// Ensures a sensor event doesn't provide values finer grained than its sensor resolution allows.
+void quantizeSensorEventValues(sensors_event_t *event, float resolution);
+
+// Provides a default resolution for simple sensor types if one wasn't provided by the HAL.
+float defaultResolutionForType(int type);
+
 class HidlServiceRegistrationWaiter : public IServiceNotification {
 public:
 
diff --git a/services/surfaceflinger/BufferLayer.cpp b/services/surfaceflinger/BufferLayer.cpp
index 54cd04f..5b28384 100644
--- a/services/surfaceflinger/BufferLayer.cpp
+++ b/services/surfaceflinger/BufferLayer.cpp
@@ -497,10 +497,6 @@
         }
     }
 
-    if (recomputeVisibleRegions == true) {
-        maybeDirtyInput();
-    }
-
     return true;
 }
 
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/LayerFECompositionState.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/LayerFECompositionState.h
index d8ce629..8a9763b 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/LayerFECompositionState.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/LayerFECompositionState.h
@@ -33,13 +33,15 @@
 #include <ui/GraphicBuffer.h>
 #include <ui/GraphicTypes.h>
 
-#include "DisplayHardware/ComposerHal.h"
+#include "DisplayHardware/Hal.h"
 
 // TODO(b/129481165): remove the #pragma below and fix conversion issues
 #pragma clang diagnostic pop // ignored "-Wconversion"
 
 namespace android::compositionengine {
 
+namespace hal = android::hardware::graphics::composer::hal;
+
 // More complex metadata for this layer
 struct GenericLayerMetadataEntry {
     // True if the metadata may affect the composed result.
@@ -108,7 +110,7 @@
     Region transparentRegionHint;
 
     // The blend mode for this layer
-    Hwc2::IComposerClient::BlendMode blendMode{Hwc2::IComposerClient::BlendMode::INVALID};
+    hal::BlendMode blendMode{hal::BlendMode::INVALID};
 
     // The bounds of the layer in layer local coordinates
     FloatRect geomLayerBounds;
@@ -145,7 +147,7 @@
      */
 
     // The type of composition for this layer
-    Hwc2::IComposerClient::Composition compositionType{Hwc2::IComposerClient::Composition::INVALID};
+    hal::Composition compositionType{hal::Composition::INVALID};
 
     // The buffer and related state
     sp<GraphicBuffer> buffer;
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h
index a5711a3..baf5258 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h
@@ -34,11 +34,13 @@
 
 #include "DisplayHardware/DisplayIdentification.h"
 
+namespace android {
+
 namespace HWC2 {
 class Layer;
 } // namespace HWC2
 
-namespace android::compositionengine {
+namespace compositionengine {
 
 class DisplayColorProfile;
 class LayerFE;
@@ -280,4 +282,5 @@
     virtual void cacheClientCompositionRequests(uint32_t cacheSize) = 0;
 };
 
-} // namespace android::compositionengine
+} // namespace compositionengine
+} // namespace android
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/OutputLayer.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/OutputLayer.h
index 007b0e8..cf77738 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/OutputLayer.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/OutputLayer.h
@@ -31,12 +31,12 @@
 // TODO(b/129481165): remove the #pragma below and fix conversion issues
 #pragma clang diagnostic pop // ignored "-Wconversion"
 
+namespace android {
+
 namespace HWC2 {
 class Layer;
 } // namespace HWC2
 
-namespace android {
-
 namespace compositionengine {
 
 class CompositionEngine;
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputLayerCompositionState.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputLayerCompositionState.h
index b0a9bc9..75394fa 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputLayerCompositionState.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputLayerCompositionState.h
@@ -36,12 +36,12 @@
 // TODO(b/129481165): remove the #pragma below and fix conversion issues
 #pragma clang diagnostic pop // ignored "-Wconversion"
 
+namespace android {
+
 namespace HWC2 {
 class Layer;
 } // namespace HWC2
 
-namespace android {
-
 class HWComposer;
 
 namespace compositionengine::impl {
diff --git a/services/surfaceflinger/CompositionEngine/src/Display.cpp b/services/surfaceflinger/CompositionEngine/src/Display.cpp
index 308ec5a..ab26939 100644
--- a/services/surfaceflinger/CompositionEngine/src/Display.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/Display.cpp
@@ -269,8 +269,8 @@
 
 bool Display::getSkipColorTransform() const {
     const auto& hwc = getCompositionEngine().getHwComposer();
-    return mId ? hwc.hasDisplayCapability(*mId, HWC2::DisplayCapability::SkipClientColorTransform)
-               : hwc.hasCapability(HWC2::Capability::SkipClientColorTransform);
+    return mId ? hwc.hasDisplayCapability(*mId, hal::DisplayCapability::SKIP_CLIENT_COLOR_TRANSFORM)
+               : hwc.hasCapability(hal::Capability::SKIP_CLIENT_COLOR_TRANSFORM);
 }
 
 bool Display::anyLayersRequireClientComposition() const {
@@ -306,7 +306,7 @@
 void Display::applyDisplayRequests(const DisplayRequests& displayRequests) {
     auto& state = editState();
     state.flipClientTarget = (static_cast<uint32_t>(displayRequests) &
-                              static_cast<uint32_t>(HWC2::DisplayRequest::FlipClientTarget)) != 0;
+                              static_cast<uint32_t>(hal::DisplayRequest::FLIP_CLIENT_TARGET)) != 0;
     // Note: HWC2::DisplayRequest::WriteClientTargetToOutput is currently ignored.
 }
 
diff --git a/services/surfaceflinger/CompositionEngine/src/OutputLayer.cpp b/services/surfaceflinger/CompositionEngine/src/OutputLayer.cpp
index 3aa7956..c9a070d 100644
--- a/services/surfaceflinger/CompositionEngine/src/OutputLayer.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/OutputLayer.cpp
@@ -344,11 +344,11 @@
 }
 
 void OutputLayer::writeOutputDependentGeometryStateToHWC(
-        HWC2::Layer* hwcLayer, Hwc2::IComposerClient::Composition requestedCompositionType) {
+        HWC2::Layer* hwcLayer, hal::Composition requestedCompositionType) {
     const auto& outputDependentState = getState();
 
     if (auto error = hwcLayer->setDisplayFrame(outputDependentState.displayFrame);
-        error != HWC2::Error::None) {
+        error != hal::Error::NONE) {
         ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
               getLayerFE().getDebugName(), outputDependentState.displayFrame.left,
               outputDependentState.displayFrame.top, outputDependentState.displayFrame.right,
@@ -357,7 +357,7 @@
     }
 
     if (auto error = hwcLayer->setSourceCrop(outputDependentState.sourceCrop);
-        error != HWC2::Error::None) {
+        error != hal::Error::NONE) {
         ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
               "%s (%d)",
               getLayerFE().getDebugName(), outputDependentState.sourceCrop.left,
@@ -366,18 +366,17 @@
               static_cast<int32_t>(error));
     }
 
-    if (auto error = hwcLayer->setZOrder(outputDependentState.z); error != HWC2::Error::None) {
+    if (auto error = hwcLayer->setZOrder(outputDependentState.z); error != hal::Error::NONE) {
         ALOGE("[%s] Failed to set Z %u: %s (%d)", getLayerFE().getDebugName(),
               outputDependentState.z, to_string(error).c_str(), static_cast<int32_t>(error));
     }
 
     // Solid-color layers should always use an identity transform.
-    const auto bufferTransform =
-            requestedCompositionType != Hwc2::IComposerClient::Composition::SOLID_COLOR
+    const auto bufferTransform = requestedCompositionType != hal::Composition::SOLID_COLOR
             ? outputDependentState.bufferTransform
-            : static_cast<Hwc2::Transform>(0);
-    if (auto error = hwcLayer->setTransform(static_cast<HWC2::Transform>(bufferTransform));
-        error != HWC2::Error::None) {
+            : static_cast<hal::Transform>(0);
+    if (auto error = hwcLayer->setTransform(static_cast<hal::Transform>(bufferTransform));
+        error != hal::Error::NONE) {
         ALOGE("[%s] Failed to set transform %s: %s (%d)", getLayerFE().getDebugName(),
               toString(outputDependentState.bufferTransform).c_str(), to_string(error).c_str(),
               static_cast<int32_t>(error));
@@ -386,30 +385,29 @@
 
 void OutputLayer::writeOutputIndependentGeometryStateToHWC(
         HWC2::Layer* hwcLayer, const LayerFECompositionState& outputIndependentState) {
-    if (auto error = hwcLayer->setBlendMode(
-                static_cast<HWC2::BlendMode>(outputIndependentState.blendMode));
-        error != HWC2::Error::None) {
+    if (auto error = hwcLayer->setBlendMode(outputIndependentState.blendMode);
+        error != hal::Error::NONE) {
         ALOGE("[%s] Failed to set blend mode %s: %s (%d)", getLayerFE().getDebugName(),
               toString(outputIndependentState.blendMode).c_str(), to_string(error).c_str(),
               static_cast<int32_t>(error));
     }
 
     if (auto error = hwcLayer->setPlaneAlpha(outputIndependentState.alpha);
-        error != HWC2::Error::None) {
+        error != hal::Error::NONE) {
         ALOGE("[%s] Failed to set plane alpha %.3f: %s (%d)", getLayerFE().getDebugName(),
               outputIndependentState.alpha, to_string(error).c_str(), static_cast<int32_t>(error));
     }
 
     if (auto error = hwcLayer->setInfo(static_cast<uint32_t>(outputIndependentState.type),
                                        static_cast<uint32_t>(outputIndependentState.appId));
-        error != HWC2::Error::None) {
+        error != hal::Error::NONE) {
         ALOGE("[%s] Failed to set info %s (%d)", getLayerFE().getDebugName(),
               to_string(error).c_str(), static_cast<int32_t>(error));
     }
 
     for (const auto& [name, entry] : outputIndependentState.metadata) {
         if (auto error = hwcLayer->setLayerGenericMetadata(name, entry.mandatory, entry.value);
-            error != HWC2::Error::None) {
+            error != hal::Error::NONE) {
             ALOGE("[%s] Failed to set generic metadata %s %s (%d)", getLayerFE().getDebugName(),
                   name.c_str(), to_string(error).c_str(), static_cast<int32_t>(error));
         }
@@ -422,14 +420,14 @@
     // TODO(lpique): b/121291683 outputSpaceVisibleRegion is output-dependent geometry
     // state and should not change every frame.
     if (auto error = hwcLayer->setVisibleRegion(outputDependentState.outputSpaceVisibleRegion);
-        error != HWC2::Error::None) {
+        error != hal::Error::NONE) {
         ALOGE("[%s] Failed to set visible region: %s (%d)", getLayerFE().getDebugName(),
               to_string(error).c_str(), static_cast<int32_t>(error));
         outputDependentState.outputSpaceVisibleRegion.dump(LOG_TAG);
     }
 
     if (auto error = hwcLayer->setDataspace(outputDependentState.dataspace);
-        error != HWC2::Error::None) {
+        error != hal::Error::NONE) {
         ALOGE("[%s] Failed to set dataspace %d: %s (%d)", getLayerFE().getDebugName(),
               outputDependentState.dataspace, to_string(error).c_str(),
               static_cast<int32_t>(error));
@@ -439,9 +437,9 @@
 void OutputLayer::writeOutputIndependentPerFrameStateToHWC(
         HWC2::Layer* hwcLayer, const LayerFECompositionState& outputIndependentState) {
     switch (auto error = hwcLayer->setColorTransform(outputIndependentState.colorTransform)) {
-        case HWC2::Error::None:
+        case hal::Error::NONE:
             break;
-        case HWC2::Error::Unsupported:
+        case hal::Error::UNSUPPORTED:
             editState().forceClientComposition = true;
             break;
         default:
@@ -450,7 +448,7 @@
     }
 
     if (auto error = hwcLayer->setSurfaceDamage(outputIndependentState.surfaceDamage);
-        error != HWC2::Error::None) {
+        error != hal::Error::NONE) {
         ALOGE("[%s] Failed to set surface damage: %s (%d)", getLayerFE().getDebugName(),
               to_string(error).c_str(), static_cast<int32_t>(error));
         outputIndependentState.surfaceDamage.dump(LOG_TAG);
@@ -458,18 +456,18 @@
 
     // Content-specific per-frame state
     switch (outputIndependentState.compositionType) {
-        case Hwc2::IComposerClient::Composition::SOLID_COLOR:
+        case hal::Composition::SOLID_COLOR:
             // For compatibility, should be written AFTER the composition type.
             break;
-        case Hwc2::IComposerClient::Composition::SIDEBAND:
+        case hal::Composition::SIDEBAND:
             writeSidebandStateToHWC(hwcLayer, outputIndependentState);
             break;
-        case Hwc2::IComposerClient::Composition::CURSOR:
-        case Hwc2::IComposerClient::Composition::DEVICE:
+        case hal::Composition::CURSOR:
+        case hal::Composition::DEVICE:
             writeBufferStateToHWC(hwcLayer, outputIndependentState);
             break;
-        case Hwc2::IComposerClient::Composition::INVALID:
-        case Hwc2::IComposerClient::Composition::CLIENT:
+        case hal::Composition::INVALID:
+        case hal::Composition::CLIENT:
             // Ignored
             break;
     }
@@ -477,16 +475,16 @@
 
 void OutputLayer::writeSolidColorStateToHWC(HWC2::Layer* hwcLayer,
                                             const LayerFECompositionState& outputIndependentState) {
-    if (outputIndependentState.compositionType != Hwc2::IComposerClient::Composition::SOLID_COLOR) {
+    if (outputIndependentState.compositionType != hal::Composition::SOLID_COLOR) {
         return;
     }
 
-    hwc_color_t color = {static_cast<uint8_t>(std::round(255.0f * outputIndependentState.color.r)),
-                         static_cast<uint8_t>(std::round(255.0f * outputIndependentState.color.g)),
-                         static_cast<uint8_t>(std::round(255.0f * outputIndependentState.color.b)),
-                         255};
+    hal::Color color = {static_cast<uint8_t>(std::round(255.0f * outputIndependentState.color.r)),
+                        static_cast<uint8_t>(std::round(255.0f * outputIndependentState.color.g)),
+                        static_cast<uint8_t>(std::round(255.0f * outputIndependentState.color.b)),
+                        255};
 
-    if (auto error = hwcLayer->setColor(color); error != HWC2::Error::None) {
+    if (auto error = hwcLayer->setColor(color); error != hal::Error::NONE) {
         ALOGE("[%s] Failed to set color: %s (%d)", getLayerFE().getDebugName(),
               to_string(error).c_str(), static_cast<int32_t>(error));
     }
@@ -495,7 +493,7 @@
 void OutputLayer::writeSidebandStateToHWC(HWC2::Layer* hwcLayer,
                                           const LayerFECompositionState& outputIndependentState) {
     if (auto error = hwcLayer->setSidebandStream(outputIndependentState.sidebandStream->handle());
-        error != HWC2::Error::None) {
+        error != hal::Error::NONE) {
         ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", getLayerFE().getDebugName(),
               outputIndependentState.sidebandStream->handle(), to_string(error).c_str(),
               static_cast<int32_t>(error));
@@ -508,7 +506,7 @@
             getOutput().getDisplayColorProfile()->getSupportedPerFrameMetadata();
     if (auto error = hwcLayer->setPerFrameMetadata(supportedPerFrameMetadata,
                                                    outputIndependentState.hdrMetadata);
-        error != HWC2::Error::None && error != HWC2::Error::Unsupported) {
+        error != hal::Error::NONE && error != hal::Error::UNSUPPORTED) {
         ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", getLayerFE().getDebugName(),
               to_string(error).c_str(), static_cast<int32_t>(error));
     }
@@ -522,29 +520,28 @@
                                                  &hwcBuffer);
 
     if (auto error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, outputIndependentState.acquireFence);
-        error != HWC2::Error::None) {
+        error != hal::Error::NONE) {
         ALOGE("[%s] Failed to set buffer %p: %s (%d)", getLayerFE().getDebugName(),
               outputIndependentState.buffer->handle, to_string(error).c_str(),
               static_cast<int32_t>(error));
     }
 }
 
-void OutputLayer::writeCompositionTypeToHWC(
-        HWC2::Layer* hwcLayer, Hwc2::IComposerClient::Composition requestedCompositionType) {
+void OutputLayer::writeCompositionTypeToHWC(HWC2::Layer* hwcLayer,
+                                            hal::Composition requestedCompositionType) {
     auto& outputDependentState = editState();
 
     // If we are forcing client composition, we need to tell the HWC
     if (outputDependentState.forceClientComposition) {
-        requestedCompositionType = Hwc2::IComposerClient::Composition::CLIENT;
+        requestedCompositionType = hal::Composition::CLIENT;
     }
 
     // Set the requested composition type with the HWC whenever it changes
     if (outputDependentState.hwc->hwcCompositionType != requestedCompositionType) {
         outputDependentState.hwc->hwcCompositionType = requestedCompositionType;
 
-        if (auto error = hwcLayer->setCompositionType(
-                    static_cast<HWC2::Composition>(requestedCompositionType));
-            error != HWC2::Error::None) {
+        if (auto error = hwcLayer->setCompositionType(requestedCompositionType);
+            error != hal::Error::NONE) {
             ALOGE("[%s] Failed to set composition type %s: %s (%d)", getLayerFE().getDebugName(),
                   toString(requestedCompositionType).c_str(), to_string(error).c_str(),
                   static_cast<int32_t>(error));
@@ -571,7 +568,7 @@
     Rect position = outputState.transform.transform(frame);
 
     if (auto error = hwcLayer->setCursorPosition(position.left, position.top);
-        error != HWC2::Error::None) {
+        error != hal::Error::NONE) {
         ALOGE("[%s] Failed to set cursor position to (%d, %d): %s (%d)",
               getLayerFE().getDebugName(), position.left, position.top, to_string(error).c_str(),
               static_cast<int32_t>(error));
@@ -585,33 +582,31 @@
 
 bool OutputLayer::requiresClientComposition() const {
     const auto& state = getState();
-    return !state.hwc ||
-            state.hwc->hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
+    return !state.hwc || state.hwc->hwcCompositionType == hal::Composition::CLIENT;
 }
 
 bool OutputLayer::isHardwareCursor() const {
     const auto& state = getState();
-    return state.hwc && state.hwc->hwcCompositionType == Hwc2::IComposerClient::Composition::CURSOR;
+    return state.hwc && state.hwc->hwcCompositionType == hal::Composition::CURSOR;
 }
 
-void OutputLayer::detectDisallowedCompositionTypeChange(
-        Hwc2::IComposerClient::Composition from, Hwc2::IComposerClient::Composition to) const {
+void OutputLayer::detectDisallowedCompositionTypeChange(hal::Composition from,
+                                                        hal::Composition to) const {
     bool result = false;
     switch (from) {
-        case Hwc2::IComposerClient::Composition::INVALID:
-        case Hwc2::IComposerClient::Composition::CLIENT:
+        case hal::Composition::INVALID:
+        case hal::Composition::CLIENT:
             result = false;
             break;
 
-        case Hwc2::IComposerClient::Composition::DEVICE:
-        case Hwc2::IComposerClient::Composition::SOLID_COLOR:
-            result = (to == Hwc2::IComposerClient::Composition::CLIENT);
+        case hal::Composition::DEVICE:
+        case hal::Composition::SOLID_COLOR:
+            result = (to == hal::Composition::CLIENT);
             break;
 
-        case Hwc2::IComposerClient::Composition::CURSOR:
-        case Hwc2::IComposerClient::Composition::SIDEBAND:
-            result = (to == Hwc2::IComposerClient::Composition::CLIENT ||
-                      to == Hwc2::IComposerClient::Composition::DEVICE);
+        case hal::Composition::CURSOR:
+        case hal::Composition::SIDEBAND:
+            result = (to == hal::Composition::CLIENT || to == hal::Composition::DEVICE);
             break;
     }
 
@@ -622,8 +617,7 @@
     }
 }
 
-void OutputLayer::applyDeviceCompositionTypeChange(
-        Hwc2::IComposerClient::Composition compositionType) {
+void OutputLayer::applyDeviceCompositionTypeChange(hal::Composition compositionType) {
     auto& state = editState();
     LOG_FATAL_IF(!state.hwc);
     auto& hwcState = *state.hwc;
@@ -638,10 +632,10 @@
     state.clearClientTarget = false;
 }
 
-void OutputLayer::applyDeviceLayerRequest(Hwc2::IComposerClient::LayerRequest request) {
+void OutputLayer::applyDeviceLayerRequest(hal::LayerRequest request) {
     auto& state = editState();
     switch (request) {
-        case Hwc2::IComposerClient::LayerRequest::CLEAR_CLIENT_TARGET:
+        case hal::LayerRequest::CLEAR_CLIENT_TARGET:
             state.clearClientTarget = true;
             break;
 
diff --git a/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp b/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
index f73a6f7..59889b6 100644
--- a/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
@@ -40,6 +40,8 @@
 namespace android::compositionengine {
 namespace {
 
+namespace hal = android::hardware::graphics::composer::hal;
+
 using testing::_;
 using testing::DoAll;
 using testing::Eq;
@@ -645,9 +647,9 @@
 
 TEST_F(DisplayChooseCompositionStrategyTest, normalOperationWithChanges) {
     android::HWComposer::DeviceRequestedChanges changes{
-            {{nullptr, HWC2::Composition::Client}},
-            HWC2::DisplayRequest::FlipClientTarget,
-            {{nullptr, HWC2::LayerRequest::ClearClientTarget}},
+            {{nullptr, hal::Composition::CLIENT}},
+            hal::DisplayRequest::FLIP_CLIENT_TARGET,
+            {{nullptr, hal::LayerRequest::CLEAR_CLIENT_TARGET}},
     };
 
     // Since two calls are made to anyLayersRequireClientComposition with different return
@@ -682,7 +684,7 @@
 using DisplayGetSkipColorTransformTest = DisplayWithLayersTestCommon;
 
 TEST_F(DisplayGetSkipColorTransformTest, checksCapabilityIfNonHwcDisplay) {
-    EXPECT_CALL(mHwComposer, hasCapability(HWC2::Capability::SkipClientColorTransform))
+    EXPECT_CALL(mHwComposer, hasCapability(hal::Capability::SKIP_CLIENT_COLOR_TRANSFORM))
             .WillOnce(Return(true));
     auto args = getDisplayCreationArgsForNonHWCVirtualDisplay();
     auto nonHwcDisplay{impl::createDisplay(mCompositionEngine, args)};
@@ -692,7 +694,7 @@
 TEST_F(DisplayGetSkipColorTransformTest, checksDisplayCapability) {
     EXPECT_CALL(mHwComposer,
                 hasDisplayCapability(DEFAULT_DISPLAY_ID,
-                                     HWC2::DisplayCapability::SkipClientColorTransform))
+                                     hal::DisplayCapability::SKIP_CLIENT_COLOR_TRANSFORM))
             .WillOnce(Return(true));
     EXPECT_TRUE(mDisplay->getSkipColorTransform());
 }
@@ -758,9 +760,9 @@
             .Times(1);
 
     mDisplay->applyChangedTypesToLayers(impl::Display::ChangedTypes{
-            {&mLayer1.hwc2Layer, HWC2::Composition::Client},
-            {&mLayer2.hwc2Layer, HWC2::Composition::Device},
-            {&hwc2LayerUnknown, HWC2::Composition::SolidColor},
+            {&mLayer1.hwc2Layer, hal::Composition::CLIENT},
+            {&mLayer2.hwc2Layer, hal::Composition::DEVICE},
+            {&hwc2LayerUnknown, hal::Composition::SOLID_COLOR},
     });
 }
 
@@ -771,28 +773,28 @@
 using DisplayApplyDisplayRequestsTest = DisplayWithLayersTestCommon;
 
 TEST_F(DisplayApplyDisplayRequestsTest, handlesNoRequests) {
-    mDisplay->applyDisplayRequests(static_cast<HWC2::DisplayRequest>(0));
+    mDisplay->applyDisplayRequests(static_cast<hal::DisplayRequest>(0));
 
     auto& state = mDisplay->getState();
     EXPECT_FALSE(state.flipClientTarget);
 }
 
 TEST_F(DisplayApplyDisplayRequestsTest, handlesFlipClientTarget) {
-    mDisplay->applyDisplayRequests(HWC2::DisplayRequest::FlipClientTarget);
+    mDisplay->applyDisplayRequests(hal::DisplayRequest::FLIP_CLIENT_TARGET);
 
     auto& state = mDisplay->getState();
     EXPECT_TRUE(state.flipClientTarget);
 }
 
 TEST_F(DisplayApplyDisplayRequestsTest, handlesWriteClientTargetToOutput) {
-    mDisplay->applyDisplayRequests(HWC2::DisplayRequest::WriteClientTargetToOutput);
+    mDisplay->applyDisplayRequests(hal::DisplayRequest::WRITE_CLIENT_TARGET_TO_OUTPUT);
 
     auto& state = mDisplay->getState();
     EXPECT_FALSE(state.flipClientTarget);
 }
 
 TEST_F(DisplayApplyDisplayRequestsTest, handlesAllRequestFlagsSet) {
-    mDisplay->applyDisplayRequests(static_cast<HWC2::DisplayRequest>(~0));
+    mDisplay->applyDisplayRequests(static_cast<hal::DisplayRequest>(~0));
 
     auto& state = mDisplay->getState();
     EXPECT_TRUE(state.flipClientTarget);
@@ -822,8 +824,8 @@
             .Times(1);
 
     mDisplay->applyLayerRequestsToLayers(impl::Display::LayerRequests{
-            {&mLayer1.hwc2Layer, HWC2::LayerRequest::ClearClientTarget},
-            {&hwc2LayerUnknown, HWC2::LayerRequest::ClearClientTarget},
+            {&mLayer1.hwc2Layer, hal::LayerRequest::CLEAR_CLIENT_TARGET},
+            {&hwc2LayerUnknown, hal::LayerRequest::CLEAR_CLIENT_TARGET},
     });
 }
 
diff --git a/services/surfaceflinger/CompositionEngine/tests/MockHWC2.cpp b/services/surfaceflinger/CompositionEngine/tests/MockHWC2.cpp
index 8c10341..0baa79d 100644
--- a/services/surfaceflinger/CompositionEngine/tests/MockHWC2.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/MockHWC2.cpp
@@ -16,7 +16,7 @@
 
 #include "MockHWC2.h"
 
-namespace HWC2 {
+namespace android::HWC2 {
 
 // This will go away once HWC2::Layer is moved into the "backend" library
 Layer::~Layer() = default;
@@ -29,4 +29,4 @@
 Layer::~Layer() = default;
 
 } // namespace mock
-} // namespace HWC2
+} // namespace android::HWC2
diff --git a/services/surfaceflinger/CompositionEngine/tests/MockHWC2.h b/services/surfaceflinger/CompositionEngine/tests/MockHWC2.h
index be89c1a..d21b97e 100644
--- a/services/surfaceflinger/CompositionEngine/tests/MockHWC2.h
+++ b/services/surfaceflinger/CompositionEngine/tests/MockHWC2.h
@@ -20,7 +20,6 @@
 #include <ui/Fence.h>
 #include <ui/FloatRect.h>
 #include <ui/GraphicBuffer.h>
-
 #include <ui/Rect.h>
 #include <ui/Region.h>
 #include <ui/Transform.h>
@@ -35,31 +34,36 @@
 // TODO(b/129481165): remove the #pragma below and fix conversion issues
 #pragma clang diagnostic pop // ignored "-Wconversion"
 
+namespace android {
 namespace HWC2 {
 namespace mock {
 
+namespace hal = android::hardware::graphics::composer::hal;
+
+using Error = hal::Error;
+
 class Layer : public HWC2::Layer {
 public:
     Layer();
     ~Layer() override;
 
-    MOCK_CONST_METHOD0(getId, hwc2_layer_t());
+    MOCK_CONST_METHOD0(getId, hal::HWLayerId());
 
     MOCK_METHOD2(setCursorPosition, Error(int32_t, int32_t));
     MOCK_METHOD3(setBuffer,
                  Error(uint32_t, const android::sp<android::GraphicBuffer>&,
                        const android::sp<android::Fence>&));
     MOCK_METHOD1(setSurfaceDamage, Error(const android::Region&));
-    MOCK_METHOD1(setBlendMode, Error(BlendMode));
-    MOCK_METHOD1(setColor, Error(hwc_color_t));
-    MOCK_METHOD1(setCompositionType, Error(Composition));
+    MOCK_METHOD1(setBlendMode, Error(hal::BlendMode));
+    MOCK_METHOD1(setColor, Error(hal::Color));
+    MOCK_METHOD1(setCompositionType, Error(hal::Composition));
     MOCK_METHOD1(setDataspace, Error(android::ui::Dataspace));
     MOCK_METHOD2(setPerFrameMetadata, Error(const int32_t, const android::HdrMetadata&));
     MOCK_METHOD1(setDisplayFrame, Error(const android::Rect&));
     MOCK_METHOD1(setPlaneAlpha, Error(float));
     MOCK_METHOD1(setSidebandStream, Error(const native_handle_t*));
     MOCK_METHOD1(setSourceCrop, Error(const android::FloatRect&));
-    MOCK_METHOD1(setTransform, Error(Transform));
+    MOCK_METHOD1(setTransform, Error(hal::Transform));
     MOCK_METHOD1(setVisibleRegion, Error(const android::Region&));
     MOCK_METHOD1(setZOrder, Error(uint32_t));
     MOCK_METHOD2(setInfo, Error(uint32_t, uint32_t));
@@ -71,3 +75,4 @@
 
 } // namespace mock
 } // namespace HWC2
+} // namespace android
diff --git a/services/surfaceflinger/CompositionEngine/tests/MockHWComposer.h b/services/surfaceflinger/CompositionEngine/tests/MockHWComposer.h
index 52bd6a1..5f42b54 100644
--- a/services/surfaceflinger/CompositionEngine/tests/MockHWComposer.h
+++ b/services/surfaceflinger/CompositionEngine/tests/MockHWComposer.h
@@ -31,6 +31,8 @@
 namespace android {
 namespace mock {
 
+namespace hal = android::hardware::graphics::composer::hal;
+
 class HWComposer : public android::HWComposer {
 public:
     HWComposer();
@@ -38,13 +40,13 @@
 
     MOCK_METHOD2(setConfiguration, void(HWC2::ComposerCallback*, int32_t));
     MOCK_CONST_METHOD3(getDisplayIdentificationData,
-                       bool(hwc2_display_t, uint8_t*, DisplayIdentificationData*));
-    MOCK_CONST_METHOD1(hasCapability, bool(HWC2::Capability));
-    MOCK_CONST_METHOD2(hasDisplayCapability, bool(DisplayId, HWC2::DisplayCapability));
+                       bool(hal::HWDisplayId, uint8_t*, DisplayIdentificationData*));
+    MOCK_CONST_METHOD1(hasCapability, bool(hal::Capability));
+    MOCK_CONST_METHOD2(hasDisplayCapability, bool(DisplayId, hal::DisplayCapability));
 
     MOCK_METHOD3(allocateVirtualDisplay,
                  std::optional<DisplayId>(uint32_t, uint32_t, ui::PixelFormat*));
-    MOCK_METHOD2(allocatePhysicalDisplay, void(hwc2_display_t, DisplayId));
+    MOCK_METHOD2(allocatePhysicalDisplay, void(hal::HWDisplayId, DisplayId));
     MOCK_METHOD1(createLayer, HWC2::Layer*(DisplayId));
     MOCK_METHOD2(destroyLayer, void(DisplayId, HWC2::Layer*));
     MOCK_METHOD3(getDeviceCompositionChanges,
@@ -76,9 +78,9 @@
     MOCK_METHOD2(getDisplayBrightnessSupport, status_t(DisplayId, bool*));
 
     MOCK_METHOD2(onHotplug,
-                 std::optional<DisplayIdentificationInfo>(hwc2_display_t, HWC2::Connection));
-    MOCK_METHOD2(onVsync, bool(hwc2_display_t, int64_t));
-    MOCK_METHOD2(setVsyncEnabled, void(DisplayId, HWC2::Vsync));
+                 std::optional<DisplayIdentificationInfo>(hal::HWDisplayId, hal::Connection));
+    MOCK_METHOD2(onVsync, bool(hal::HWDisplayId, int64_t));
+    MOCK_METHOD2(setVsyncEnabled, void(DisplayId, hal::Vsync));
     MOCK_CONST_METHOD1(getRefreshTimestamp, nsecs_t(DisplayId));
     MOCK_CONST_METHOD1(isConnected, bool(DisplayId));
     MOCK_CONST_METHOD1(getConfigs,
@@ -92,21 +94,21 @@
     MOCK_CONST_METHOD1(isVsyncPeriodSwitchSupported, bool(DisplayId));
     MOCK_CONST_METHOD1(getDisplayVsyncPeriod, nsecs_t(DisplayId));
     MOCK_METHOD4(setActiveConfigWithConstraints,
-                 status_t(DisplayId, size_t, const HWC2::VsyncPeriodChangeConstraints&,
-                          HWC2::VsyncPeriodChangeTimeline*));
+                 status_t(DisplayId, size_t, const hal::VsyncPeriodChangeConstraints&,
+                          hal::VsyncPeriodChangeTimeline*));
     MOCK_METHOD2(setAutoLowLatencyMode, status_t(DisplayId, bool));
-    MOCK_METHOD2(getSupportedContentTypes, status_t(DisplayId, std::vector<HWC2::ContentType>*));
-    MOCK_METHOD2(setContentType, status_t(DisplayId, HWC2::ContentType));
+    MOCK_METHOD2(getSupportedContentTypes, status_t(DisplayId, std::vector<hal::ContentType>*));
+    MOCK_METHOD2(setContentType, status_t(DisplayId, hal::ContentType));
     MOCK_CONST_METHOD0(getSupportedLayerGenericMetadata,
                        const std::unordered_map<std::string, bool>&());
 
     MOCK_CONST_METHOD1(dump, void(std::string&));
     MOCK_CONST_METHOD0(getComposer, android::Hwc2::Composer*());
-    MOCK_CONST_METHOD1(getHwcDisplayId, std::optional<hwc2_display_t>(int32_t));
-    MOCK_CONST_METHOD0(getInternalHwcDisplayId, std::optional<hwc2_display_t>());
-    MOCK_CONST_METHOD0(getExternalHwcDisplayId, std::optional<hwc2_display_t>());
-    MOCK_CONST_METHOD1(toPhysicalDisplayId, std::optional<DisplayId>(hwc2_display_t));
-    MOCK_CONST_METHOD1(fromPhysicalDisplayId, std::optional<hwc2_display_t>(DisplayId));
+    MOCK_CONST_METHOD1(getHwcDisplayId, std::optional<hal::HWDisplayId>(int32_t));
+    MOCK_CONST_METHOD0(getInternalHwcDisplayId, std::optional<hal::HWDisplayId>());
+    MOCK_CONST_METHOD0(getExternalHwcDisplayId, std::optional<hal::HWDisplayId>());
+    MOCK_CONST_METHOD1(toPhysicalDisplayId, std::optional<DisplayId>(hal::HWDisplayId));
+    MOCK_CONST_METHOD1(fromPhysicalDisplayId, std::optional<hal::HWDisplayId>(DisplayId));
 };
 
 } // namespace mock
diff --git a/services/surfaceflinger/CompositionEngine/tests/OutputLayerTest.cpp b/services/surfaceflinger/CompositionEngine/tests/OutputLayerTest.cpp
index 1b5617c..266f91d 100644
--- a/services/surfaceflinger/CompositionEngine/tests/OutputLayerTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/OutputLayerTest.cpp
@@ -29,6 +29,8 @@
 namespace android::compositionengine {
 namespace {
 
+namespace hal = android::hardware::graphics::composer::hal;
+
 using testing::_;
 using testing::InSequence;
 using testing::Return;
@@ -613,7 +615,7 @@
  */
 
 struct OutputLayerWriteStateToHWCTest : public OutputLayerTest {
-    static constexpr HWC2::Error kError = HWC2::Error::Unsupported;
+    static constexpr hal::Error kError = hal::Error::UNSUPPORTED;
     static constexpr FloatRect kSourceCrop{11.f, 12.f, 13.f, 14.f};
     static constexpr uint32_t kZOrder = 21u;
     static constexpr Hwc2::Transform kBufferTransform = static_cast<Hwc2::Transform>(31);
@@ -686,11 +688,9 @@
         EXPECT_CALL(*mHwcLayer, setDisplayFrame(kDisplayFrame)).WillOnce(Return(kError));
         EXPECT_CALL(*mHwcLayer, setSourceCrop(kSourceCrop)).WillOnce(Return(kError));
         EXPECT_CALL(*mHwcLayer, setZOrder(kZOrder)).WillOnce(Return(kError));
-        EXPECT_CALL(*mHwcLayer, setTransform(static_cast<HWC2::Transform>(kBufferTransform)))
-                .WillOnce(Return(kError));
+        EXPECT_CALL(*mHwcLayer, setTransform(kBufferTransform)).WillOnce(Return(kError));
 
-        EXPECT_CALL(*mHwcLayer, setBlendMode(static_cast<HWC2::BlendMode>(kBlendMode)))
-                .WillOnce(Return(kError));
+        EXPECT_CALL(*mHwcLayer, setBlendMode(kBlendMode)).WillOnce(Return(kError));
         EXPECT_CALL(*mHwcLayer, setPlaneAlpha(kAlpha)).WillOnce(Return(kError));
         EXPECT_CALL(*mHwcLayer, setInfo(kType, kAppId)).WillOnce(Return(kError));
     }
@@ -701,15 +701,14 @@
         EXPECT_CALL(*mHwcLayer, setDataspace(kDataspace)).WillOnce(Return(kError));
         EXPECT_CALL(*mHwcLayer, setColorTransform(kColorTransform))
                 .WillOnce(Return(unsupported == SimulateUnsupported::ColorTransform
-                                         ? HWC2::Error::Unsupported
-                                         : HWC2::Error::None));
+                                         ? hal::Error::UNSUPPORTED
+                                         : hal::Error::NONE));
         EXPECT_CALL(*mHwcLayer, setSurfaceDamage(RegionEq(kSurfaceDamage)))
                 .WillOnce(Return(kError));
     }
 
     void expectSetCompositionTypeCall(Hwc2::IComposerClient::Composition compositionType) {
-        EXPECT_CALL(*mHwcLayer, setCompositionType(static_cast<HWC2::Composition>(compositionType)))
-                .WillOnce(Return(kError));
+        EXPECT_CALL(*mHwcLayer, setCompositionType(compositionType)).WillOnce(Return(kError));
     }
 
     void expectNoSetCompositionTypeCall() {
@@ -924,7 +923,7 @@
 
 struct OutputLayerWriteCursorPositionToHWCTest : public OutputLayerTest {
     static constexpr int kDefaultTransform = TR_IDENT;
-    static constexpr HWC2::Error kDefaultError = HWC2::Error::Unsupported;
+    static constexpr hal::Error kDefaultError = hal::Error::UNSUPPORTED;
 
     static const Rect kDefaultDisplayViewport;
     static const Rect kDefaultCursorFrame;
diff --git a/services/surfaceflinger/DisplayDevice.h b/services/surfaceflinger/DisplayDevice.h
index e670d78..2b19cc5 100644
--- a/services/surfaceflinger/DisplayDevice.h
+++ b/services/surfaceflinger/DisplayDevice.h
@@ -39,6 +39,7 @@
 #include <utils/Timers.h>
 
 #include "DisplayHardware/DisplayIdentification.h"
+#include "DisplayHardware/Hal.h"
 #include "DisplayHardware/PowerAdvisor.h"
 #include "RenderArea.h"
 #include "Scheduler/HwcStrongTypes.h"
@@ -183,7 +184,7 @@
     struct Physical {
         DisplayId id;
         DisplayConnectionType type;
-        hwc2_display_t hwcDisplayId;
+        android::hardware::graphics::composer::hal::HWDisplayId hwcDisplayId;
 
         bool operator==(const Physical& other) const {
             return id == other.id && type == other.type && hwcDisplayId == other.hwcDisplayId;
diff --git a/services/surfaceflinger/DisplayHardware/HWC2.cpp b/services/surfaceflinger/DisplayHardware/HWC2.cpp
index fc5d441..d6dbd57 100644
--- a/services/surfaceflinger/DisplayHardware/HWC2.cpp
+++ b/services/surfaceflinger/DisplayHardware/HWC2.cpp
@@ -38,6 +38,8 @@
 #include <iterator>
 #include <set>
 
+namespace android {
+
 using android::Fence;
 using android::FloatRect;
 using android::GraphicBuffer;
@@ -49,11 +51,9 @@
 
 namespace HWC2 {
 
+using namespace android::hardware::graphics::composer::hal;
+
 namespace Hwc2 = android::Hwc2;
-using android::ui::ColorMode;
-using android::ui::Dataspace;
-using android::ui::PixelFormat;
-using android::ui::RenderIntent;
 
 namespace {
 
@@ -67,7 +67,7 @@
 // Display methods
 Display::~Display() = default;
 
-Display::Config::Config(Display& display, hwc2_config_t id)
+Display::Config::Config(Display& display, HWConfigId id)
       : mDisplay(display),
         mId(id),
         mWidth(-1),
@@ -76,7 +76,7 @@
         mDpiX(-1),
         mDpiY(-1) {}
 
-Display::Config::Builder::Builder(Display& display, hwc2_config_t id)
+Display::Config::Builder::Builder(Display& display, HWConfigId id)
       : mConfig(new Config(display, id)) {}
 
 float Display::Config::Builder::getDefaultDensity() {
@@ -97,37 +97,34 @@
 namespace impl {
 
 Display::Display(android::Hwc2::Composer& composer,
-                 const std::unordered_set<Capability>& capabilities, hwc2_display_t id,
+                 const std::unordered_set<Capability>& capabilities, HWDisplayId id,
                  DisplayType type)
-      : mComposer(composer),
-        mCapabilities(capabilities),
-        mId(id),
-        mType(type) {
+      : mComposer(composer), mCapabilities(capabilities), mId(id), mType(type) {
     ALOGV("Created display %" PRIu64, id);
 }
 
 Display::~Display() {
     mLayers.clear();
 
-    Error error = Error::None;
+    Error error = Error::NONE;
     const char* msg;
     switch (mType) {
-        case DisplayType::Physical:
-            error = setVsyncEnabled(HWC2::Vsync::Disable);
+        case DisplayType::PHYSICAL:
+            error = setVsyncEnabled(HWC2::Vsync::DISABLE);
             msg = "disable VSYNC for";
             break;
 
-        case DisplayType::Virtual:
+        case DisplayType::VIRTUAL:
             error = static_cast<Error>(mComposer.destroyVirtualDisplay(mId));
             msg = "destroy virtual";
             break;
 
-        case DisplayType::Invalid: // Used in unit tests.
+        case DisplayType::INVALID: // Used in unit tests.
             break;
     }
 
-    ALOGE_IF(error != Error::None, "%s: Failed to %s display %" PRIu64 ": %s (%d)", __FUNCTION__,
-             msg, mId, to_string(error).c_str(), static_cast<int32_t>(error));
+    ALOGE_IF(error != Error::NONE, "%s: Failed to %s display %" PRIu64 ": %d", __FUNCTION__, msg,
+             mId, static_cast<int32_t>(error));
 
     ALOGV("Destroyed display %" PRIu64, mId);
 }
@@ -141,38 +138,38 @@
 
 Error Display::createLayer(HWC2::Layer** outLayer) {
     if (!outLayer) {
-        return Error::BadParameter;
+        return Error::BAD_PARAMETER;
     }
-    hwc2_layer_t layerId = 0;
+    HWLayerId layerId = 0;
     auto intError = mComposer.createLayer(mId, &layerId);
     auto error = static_cast<Error>(intError);
-    if (error != Error::None) {
+    if (error != Error::NONE) {
         return error;
     }
 
     auto layer = std::make_unique<impl::Layer>(mComposer, mCapabilities, mId, layerId);
     *outLayer = layer.get();
     mLayers.emplace(layerId, std::move(layer));
-    return Error::None;
+    return Error::NONE;
 }
 
 Error Display::destroyLayer(HWC2::Layer* layer) {
     if (!layer) {
-        return Error::BadParameter;
+        return Error::BAD_PARAMETER;
     }
     mLayers.erase(layer->getId());
-    return Error::None;
+    return Error::NONE;
 }
 
 Error Display::getActiveConfig(
         std::shared_ptr<const Display::Config>* outConfig) const
 {
     ALOGV("[%" PRIu64 "] getActiveConfig", mId);
-    hwc2_config_t configId = 0;
+    HWConfigId configId = 0;
     auto intError = mComposer.getActiveConfig(mId, &configId);
     auto error = static_cast<Error>(intError);
 
-    if (error != Error::None) {
+    if (error != Error::NONE) {
         ALOGE("Unable to get active config for mId:[%" PRIu64 "]", mId);
         *outConfig = nullptr;
         return error;
@@ -188,7 +185,7 @@
         *outConfig = nullptr;
     }
 
-    return Error::None;
+    return Error::NONE;
 }
 
 bool Display::isVsyncPeriodSwitchSupported() const {
@@ -209,10 +206,10 @@
         *outVsyncPeriod = static_cast<nsecs_t>(vsyncPeriodNanos);
     } else {
         // Get the default vsync period
-        hwc2_config_t configId = 0;
+        HWConfigId configId = 0;
         auto intError_2_1 = mComposer.getActiveConfig(mId, &configId);
         error = static_cast<Error>(intError_2_1);
-        if (error == Error::None) {
+        if (error == Error::NONE) {
             auto config = mConfigs.at(configId);
             *outVsyncPeriod = config->getVsyncPeriod();
         }
@@ -223,11 +220,11 @@
 
 Error Display::getActiveConfigIndex(int* outIndex) const {
     ALOGV("[%" PRIu64 "] getActiveConfigIndex", mId);
-    hwc2_config_t configId = 0;
+    HWConfigId configId = 0;
     auto intError = mComposer.getActiveConfig(mId, &configId);
     auto error = static_cast<Error>(intError);
 
-    if (error != Error::None) {
+    if (error != Error::NONE) {
         ALOGE("Unable to get active config for mId:[%" PRIu64 "]", mId);
         *outIndex = -1;
         return error;
@@ -244,7 +241,7 @@
         *outIndex = -1;
     }
 
-    return Error::None;
+    return Error::NONE;
 }
 
 Error Display::getChangedCompositionTypes(std::unordered_map<HWC2::Layer*, Composition>* outTypes) {
@@ -255,7 +252,7 @@
     uint32_t numElements = layerIds.size();
     auto error = static_cast<Error>(intError);
     error = static_cast<Error>(intError);
-    if (error != Error::None) {
+    if (error != Error::NONE) {
         return error;
     }
 
@@ -264,7 +261,7 @@
     for (uint32_t element = 0; element < numElements; ++element) {
         auto layer = getLayerById(layerIds[element]);
         if (layer) {
-            auto type = static_cast<Composition>(types[element]);
+            auto type = types[element];
             ALOGV("getChangedCompositionTypes: adding %" PRIu64 " %s",
                     layer->getId(), to_string(type).c_str());
             outTypes->emplace(layer, type);
@@ -274,7 +271,7 @@
         }
     }
 
-    return Error::None;
+    return Error::NONE;
 }
 
 Error Display::getColorModes(std::vector<ColorMode>* outModes) const
@@ -357,7 +354,7 @@
             mId, &intDisplayRequests, &layerIds, &layerRequests);
     uint32_t numElements = layerIds.size();
     auto error = static_cast<Error>(intError);
-    if (error != Error::None) {
+    if (error != Error::NONE) {
         return error;
     }
 
@@ -376,28 +373,28 @@
         }
     }
 
-    return Error::None;
+    return Error::NONE;
 }
 
 Error Display::getConnectionType(android::DisplayConnectionType* outType) const {
-    if (mType != DisplayType::Physical) return Error::BadDisplay;
+    if (mType != DisplayType::PHYSICAL) return Error::BAD_DISPLAY;
 
     using ConnectionType = Hwc2::IComposerClient::DisplayConnectionType;
     ConnectionType connectionType;
     const auto error = static_cast<Error>(mComposer.getDisplayConnectionType(mId, &connectionType));
-    if (error != Error::None) {
+    if (error != Error::NONE) {
         return error;
     }
 
     *outType = connectionType == ConnectionType::INTERNAL
             ? android::DisplayConnectionType::Internal
             : android::DisplayConnectionType::External;
-    return Error::None;
+    return Error::NONE;
 }
 
 Error Display::supportsDoze(bool* outSupport) const {
-    *outSupport = mDisplayCapabilities.count(DisplayCapability::Doze) > 0;
-    return Error::None;
+    *outSupport = mDisplayCapabilities.count(DisplayCapability::DOZE) > 0;
+    return Error::NONE;
 }
 
 Error Display::getHdrCapabilities(HdrCapabilities* outCapabilities) const
@@ -410,16 +407,16 @@
             &maxLuminance, &maxAverageLuminance, &minLuminance);
     auto error = static_cast<HWC2::Error>(intError);
 
-    if (error != Error::None) {
+    if (error != Error::NONE) {
         return error;
     }
 
     *outCapabilities = HdrCapabilities(std::move(types),
             maxLuminance, maxAverageLuminance, minLuminance);
-    return Error::None;
+    return Error::NONE;
 }
 
-Error Display::getDisplayedContentSamplingAttributes(PixelFormat* outFormat,
+Error Display::getDisplayedContentSamplingAttributes(hal::PixelFormat* outFormat,
                                                      Dataspace* outDataspace,
                                                      uint8_t* outComponentMask) const {
     auto intError = mComposer.getDisplayedContentSamplingAttributes(mId, outFormat, outDataspace,
@@ -446,7 +443,7 @@
     auto intError = mComposer.getReleaseFences(mId, &layerIds, &fenceFds);
     auto error = static_cast<Error>(intError);
     uint32_t numElements = layerIds.size();
-    if (error != Error::None) {
+    if (error != Error::NONE) {
         return error;
     }
 
@@ -463,12 +460,12 @@
             for (; element < numElements; ++element) {
                 close(fenceFds[element]);
             }
-            return Error::BadLayer;
+            return Error::BAD_LAYER;
         }
     }
 
     *outFences = std::move(releaseFences);
-    return Error::None;
+    return Error::NONE;
 }
 
 Error Display::present(sp<Fence>* outPresentFence)
@@ -476,12 +473,12 @@
     int32_t presentFenceFd = -1;
     auto intError = mComposer.presentDisplay(mId, &presentFenceFd);
     auto error = static_cast<Error>(intError);
-    if (error != Error::None) {
+    if (error != Error::NONE) {
         return error;
     }
 
     *outPresentFence = new Fence(presentFenceFd);
-    return Error::None;
+    return Error::NONE;
 }
 
 Error Display::setActiveConfigWithConstraints(
@@ -492,7 +489,7 @@
         ALOGE("setActiveConfigWithConstraints received config %u for the wrong display %" PRIu64
               " (expected %" PRIu64 ")",
               config->getId(), config->getDisplayId(), mId);
-        return Error::BadConfig;
+        return Error::BAD_CONFIG;
     }
 
     if (isVsyncPeriodSwitchSupported()) {
@@ -530,7 +527,7 @@
         ALOGE("setActiveConfig received config %u for the wrong display %"
                 PRIu64 " (expected %" PRIu64 ")", config->getId(),
                 config->getDisplayId(), mId);
-        return Error::BadConfig;
+        return Error::BAD_CONFIG;
     }
     auto intError = mComposer.setActiveConfig(mId, config->getId());
     return static_cast<Error>(intError);
@@ -552,11 +549,8 @@
     return static_cast<Error>(intError);
 }
 
-Error Display::setColorTransform(const android::mat4& matrix,
-        android_color_transform_t hint)
-{
-    auto intError = mComposer.setColorTransform(mId,
-            matrix.asArray(), static_cast<Hwc2::ColorTransform>(hint));
+Error Display::setColorTransform(const android::mat4& matrix, ColorTransform hint) {
+    auto intError = mComposer.setColorTransform(mId, matrix.asArray(), hint);
     return static_cast<Error>(intError);
 }
 
@@ -575,23 +569,23 @@
     auto intMode = static_cast<Hwc2::IComposerClient::PowerMode>(mode);
     auto intError = mComposer.setPowerMode(mId, intMode);
 
-    if (mode == PowerMode::On) {
+    if (mode == PowerMode::ON) {
         std::call_once(mDisplayCapabilityQueryFlag, [this]() {
             std::vector<Hwc2::DisplayCapability> tmpCapabilities;
             auto error =
                     static_cast<Error>(mComposer.getDisplayCapabilities(mId, &tmpCapabilities));
-            if (error == Error::None) {
+            if (error == Error::NONE) {
                 for (auto capability : tmpCapabilities) {
                     mDisplayCapabilities.emplace(static_cast<DisplayCapability>(capability));
                 }
-            } else if (error == Error::Unsupported) {
-                if (mCapabilities.count(Capability::SkipClientColorTransform)) {
-                    mDisplayCapabilities.emplace(DisplayCapability::SkipClientColorTransform);
+            } else if (error == Error::UNSUPPORTED) {
+                if (mCapabilities.count(Capability::SKIP_CLIENT_COLOR_TRANSFORM)) {
+                    mDisplayCapabilities.emplace(DisplayCapability::SKIP_CLIENT_COLOR_TRANSFORM);
                 }
                 bool dozeSupport = false;
                 error = static_cast<Error>(mComposer.getDozeSupport(mId, &dozeSupport));
-                if (error == Error::None && dozeSupport) {
-                    mDisplayCapabilities.emplace(DisplayCapability::Doze);
+                if (error == Error::NONE && dozeSupport) {
+                    mDisplayCapabilities.emplace(DisplayCapability::DOZE);
                 }
             }
         });
@@ -613,7 +607,7 @@
     uint32_t numRequests = 0;
     auto intError = mComposer.validateDisplay(mId, &numTypes, &numRequests);
     auto error = static_cast<Error>(intError);
-    if (error != Error::None && error != Error::HasChanges) {
+    if (error != Error::NONE && !hasChangesError(error)) {
         return error;
     }
 
@@ -631,7 +625,7 @@
     auto intError = mComposer.presentOrValidateDisplay(
             mId, &numTypes, &numRequests, &presentFenceFd, state);
     auto error = static_cast<Error>(intError);
-    if (error != Error::None && error != Error::HasChanges) {
+    if (error != Error::NONE && !hasChangesError(error)) {
         return error;
     }
 
@@ -647,7 +641,7 @@
 }
 
 Error Display::setDisplayBrightness(float brightness) const {
-    auto intError = mComposer.setDisplayBrightness(mId, brightness);
+    const auto intError = mComposer.setDisplayBrightness(mId, brightness);
     return static_cast<Error>(intError);
 }
 
@@ -666,8 +660,7 @@
 }
 
 Error Display::setContentType(ContentType contentType) const {
-    using Hwc2_ContentType = Hwc2::IComposerClient::ContentType;
-    auto intError = mComposer.setContentType(mId, static_cast<Hwc2_ContentType>(contentType));
+    auto intError = mComposer.setContentType(mId, contentType);
     return static_cast<Error>(intError);
 }
 
@@ -676,21 +669,18 @@
 void Display::setConnected(bool connected) {
     if (!mIsConnected && connected) {
         mComposer.setClientTargetSlotCount(mId);
-        if (mType == DisplayType::Physical) {
+        if (mType == DisplayType::PHYSICAL) {
             loadConfigs();
         }
     }
     mIsConnected = connected;
 }
 
-int32_t Display::getAttribute(hwc2_config_t configId, Attribute attribute)
-{
+int32_t Display::getAttribute(HWConfigId configId, Attribute attribute) {
     int32_t value = 0;
-    auto intError = mComposer.getDisplayAttribute(mId, configId,
-            static_cast<Hwc2::IComposerClient::Attribute>(attribute),
-            &value);
+    auto intError = mComposer.getDisplayAttribute(mId, configId, attribute, &value);
     auto error = static_cast<Error>(intError);
-    if (error != Error::None) {
+    if (error != Error::NONE) {
         ALOGE("getDisplayAttribute(%" PRIu64 ", %u, %s) failed: %s (%d)", mId,
                 configId, to_string(attribute).c_str(),
                 to_string(error).c_str(), intError);
@@ -699,17 +689,16 @@
     return value;
 }
 
-void Display::loadConfig(hwc2_config_t configId)
-{
+void Display::loadConfig(HWConfigId configId) {
     ALOGV("[%" PRIu64 "] loadConfig(%u)", mId, configId);
 
     auto config = Config::Builder(*this, configId)
-                          .setWidth(getAttribute(configId, Attribute::Width))
-                          .setHeight(getAttribute(configId, Attribute::Height))
-                          .setVsyncPeriod(getAttribute(configId, Attribute::VsyncPeriod))
-                          .setDpiX(getAttribute(configId, Attribute::DpiX))
-                          .setDpiY(getAttribute(configId, Attribute::DpiY))
-                          .setConfigGroup(getAttribute(configId, Attribute::ConfigGroup))
+                          .setWidth(getAttribute(configId, hal::Attribute::WIDTH))
+                          .setHeight(getAttribute(configId, hal::Attribute::HEIGHT))
+                          .setVsyncPeriod(getAttribute(configId, hal::Attribute::VSYNC_PERIOD))
+                          .setDpiX(getAttribute(configId, hal::Attribute::DPI_X))
+                          .setDpiY(getAttribute(configId, hal::Attribute::DPI_Y))
+                          .setConfigGroup(getAttribute(configId, hal::Attribute::CONFIG_GROUP))
                           .build();
     mConfigs.emplace(configId, std::move(config));
 }
@@ -718,10 +707,10 @@
 {
     ALOGV("[%" PRIu64 "] loadConfigs", mId);
 
-    std::vector<Hwc2::Config> configIds;
+    std::vector<HWConfigId> configIds;
     auto intError = mComposer.getDisplayConfigs(mId, &configIds);
     auto error = static_cast<Error>(intError);
-    if (error != Error::None) {
+    if (error != Error::NONE) {
         ALOGE("[%" PRIu64 "] getDisplayConfigs [2] failed: %s (%d)", mId,
                 to_string(error).c_str(), intError);
         return;
@@ -734,7 +723,7 @@
 
 // Other Display methods
 
-HWC2::Layer* Display::getLayerById(hwc2_layer_t id) const {
+HWC2::Layer* Display::getLayerById(HWLayerId id) const {
     if (mLayers.count(id) == 0) {
         return nullptr;
     }
@@ -750,7 +739,7 @@
 namespace impl {
 
 Layer::Layer(android::Hwc2::Composer& composer, const std::unordered_set<Capability>& capabilities,
-             hwc2_display_t displayId, hwc2_layer_t layerId)
+             HWDisplayId displayId, HWLayerId layerId)
       : mComposer(composer),
         mCapabilities(capabilities),
         mDisplayId(displayId),
@@ -763,9 +752,10 @@
 {
     auto intError = mComposer.destroyLayer(mDisplayId, mId);
     auto error = static_cast<Error>(intError);
-    ALOGE_IF(error != Error::None, "destroyLayer(%" PRIu64 ", %" PRIu64 ")"
-            " failed: %s (%d)", mDisplayId, mId, to_string(error).c_str(),
-            intError);
+    ALOGE_IF(error != Error::NONE,
+             "destroyLayer(%" PRIu64 ", %" PRIu64 ")"
+             " failed: %s (%d)",
+             mDisplayId, mId, to_string(error).c_str(), intError);
 }
 
 Error Layer::setCursorPosition(int32_t x, int32_t y)
@@ -778,7 +768,7 @@
         const sp<Fence>& acquireFence)
 {
     if (buffer == nullptr && mBufferSlot == slot) {
-        return Error::None;
+        return Error::NONE;
     }
     mBufferSlot = slot;
 
@@ -792,7 +782,7 @@
 {
     if (damage.isRect() && mDamageRegion.isRect() &&
         (damage.getBounds() == mDamageRegion.getBounds())) {
-        return Error::None;
+        return Error::NONE;
     }
     mDamageRegion = damage;
 
@@ -820,30 +810,25 @@
 
 Error Layer::setBlendMode(BlendMode mode)
 {
-    auto intMode = static_cast<Hwc2::IComposerClient::BlendMode>(mode);
-    auto intError = mComposer.setLayerBlendMode(mDisplayId, mId, intMode);
+    auto intError = mComposer.setLayerBlendMode(mDisplayId, mId, mode);
     return static_cast<Error>(intError);
 }
 
-Error Layer::setColor(hwc_color_t color)
-{
-    Hwc2::IComposerClient::Color hwcColor{color.r, color.g, color.b, color.a};
-    auto intError = mComposer.setLayerColor(mDisplayId, mId, hwcColor);
+Error Layer::setColor(Color color) {
+    auto intError = mComposer.setLayerColor(mDisplayId, mId, color);
     return static_cast<Error>(intError);
 }
 
 Error Layer::setCompositionType(Composition type)
 {
-    auto intType = static_cast<Hwc2::IComposerClient::Composition>(type);
-    auto intError = mComposer.setLayerCompositionType(
-            mDisplayId, mId, intType);
+    auto intError = mComposer.setLayerCompositionType(mDisplayId, mId, type);
     return static_cast<Error>(intError);
 }
 
 Error Layer::setDataspace(Dataspace dataspace)
 {
     if (dataspace == mDataSpace) {
-        return Error::None;
+        return Error::NONE;
     }
     mDataSpace = dataspace;
     auto intError = mComposer.setLayerDataspace(mDisplayId, mId, mDataSpace);
@@ -854,7 +839,7 @@
         const android::HdrMetadata& metadata)
 {
     if (metadata == mHdrMetadata) {
-        return Error::None;
+        return Error::NONE;
     }
 
     mHdrMetadata = metadata;
@@ -901,7 +886,7 @@
                 {Hwc2::PerFrameMetadataKey::HDR10_PLUS_SEI, mHdrMetadata.hdr10plus});
         Error setMetadataBlobsError = static_cast<Error>(
                 mComposer.setLayerPerFrameMetadataBlobs(mDisplayId, mId, perFrameMetadataBlobs));
-        if (error == Error::None) {
+        if (error == Error::NONE) {
             return setMetadataBlobsError;
         }
     }
@@ -924,10 +909,10 @@
 
 Error Layer::setSidebandStream(const native_handle_t* stream)
 {
-    if (mCapabilities.count(Capability::SidebandStream) == 0) {
+    if (mCapabilities.count(Capability::SIDEBAND_STREAM) == 0) {
         ALOGE("Attempted to call setSidebandStream without checking that the "
                 "device supports sideband streams");
-        return Error::Unsupported;
+        return Error::UNSUPPORTED;
     }
     auto intError = mComposer.setLayerSidebandStream(mDisplayId, mId, stream);
     return static_cast<Error>(intError);
@@ -952,7 +937,7 @@
 {
     if (region.isRect() && mVisibleRegion.isRect() &&
         (region.getBounds() == mVisibleRegion.getBounds())) {
-        return Error::None;
+        return Error::NONE;
     }
     mVisibleRegion = region;
 
@@ -984,11 +969,11 @@
 // Composer HAL 2.3
 Error Layer::setColorTransform(const android::mat4& matrix) {
     if (matrix == mColorMatrix) {
-        return Error::None;
+        return Error::NONE;
     }
     auto intError = mComposer.setLayerColorTransform(mDisplayId, mId, matrix.asArray());
     Error error = static_cast<Error>(intError);
-    if (error != Error::None) {
+    if (error != Error::NONE) {
         return error;
     }
     mColorMatrix = matrix;
@@ -1004,6 +989,7 @@
 
 } // namespace impl
 } // namespace HWC2
+} // namespace android
 
 // TODO(b/129481165): remove the #pragma below and fix conversion issues
 #pragma clang diagnostic pop // ignored "-Wconversion"
diff --git a/services/surfaceflinger/DisplayHardware/HWC2.h b/services/surfaceflinger/DisplayHardware/HWC2.h
index 6549525..af31df8 100644
--- a/services/surfaceflinger/DisplayHardware/HWC2.h
+++ b/services/surfaceflinger/DisplayHardware/HWC2.h
@@ -17,16 +17,9 @@
 #ifndef ANDROID_SF_HWC2_H
 #define ANDROID_SF_HWC2_H
 
-#define HWC2_INCLUDE_STRINGIFICATION
-#define HWC2_USE_CPP11
-#include <hardware/hwcomposer2.h>
-#undef HWC2_INCLUDE_STRINGIFICATION
-#undef HWC2_USE_CPP11
-
 #include <gui/HdrMetadata.h>
 #include <math/mat4.h>
 #include <ui/DisplayInfo.h>
-#include <ui/GraphicTypes.h>
 #include <ui/HdrCapabilities.h>
 #include <ui/Region.h>
 #include <utils/Log.h>
@@ -39,6 +32,8 @@
 #include <unordered_set>
 #include <vector>
 
+#include "Hal.h"
+
 namespace android {
     struct DisplayedFrameStats;
     class Fence;
@@ -49,13 +44,12 @@
     }
 
     class TestableSurfaceFlinger;
-}
 
 namespace HWC2 {
 
 class Layer;
-using VsyncPeriodChangeConstraints = hwc_vsync_period_change_constraints_t;
-using VsyncPeriodChangeTimeline = hwc_vsync_period_change_timeline_t;
+
+namespace hal = android::hardware::graphics::composer::hal;
 
 // Implement this interface to receive hardware composer events.
 //
@@ -68,21 +62,20 @@
 // from different hardware composer instances.
 class ComposerCallback {
  public:
-    virtual void onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
-                                   Connection connection) = 0;
-    virtual void onRefreshReceived(int32_t sequenceId,
-                                   hwc2_display_t display) = 0;
-    virtual void onVsyncReceived(int32_t sequenceId, hwc2_display_t display, int64_t timestamp,
-                                 std::optional<hwc2_vsync_period_t> vsyncPeriod) = 0;
-    virtual void onVsyncPeriodTimingChangedReceived(
-            int32_t sequenceId, hwc2_display_t display,
-            const hwc_vsync_period_change_timeline_t& updatedTimeline) = 0;
-    virtual void onSeamlessPossible(int32_t sequenceId, hwc2_display_t display) = 0;
+     virtual void onHotplugReceived(int32_t sequenceId, hal::HWDisplayId display,
+                                    hal::Connection connection) = 0;
+     virtual void onRefreshReceived(int32_t sequenceId, hal::HWDisplayId display) = 0;
+     virtual void onVsyncReceived(int32_t sequenceId, hal::HWDisplayId display, int64_t timestamp,
+                                  std::optional<hal::VsyncPeriodNanos> vsyncPeriod) = 0;
+     virtual void onVsyncPeriodTimingChangedReceived(
+             int32_t sequenceId, hal::HWDisplayId display,
+             const hal::VsyncPeriodChangeTimeline& updatedTimeline) = 0;
+     virtual void onSeamlessPossible(int32_t sequenceId, hal::HWDisplayId display) = 0;
 
-    virtual ~ComposerCallback() = default;
+     virtual ~ComposerCallback() = default;
 };
 
-// Convenience C++ class to access hwc2_device_t Display functions directly.
+// Convenience C++ class to access per display functions directly.
 class Display {
 public:
     virtual ~Display();
@@ -92,7 +85,7 @@
         class Builder
         {
         public:
-            Builder(Display& display, hwc2_config_t id);
+            Builder(Display& display, hal::HWConfigId id);
 
             std::shared_ptr<const Config> build() {
                 return std::const_pointer_cast<const Config>(
@@ -137,8 +130,8 @@
             std::shared_ptr<Config> mConfig;
         };
 
-        hwc2_display_t getDisplayId() const { return mDisplay.getId(); }
-        hwc2_config_t getId() const { return mId; }
+        hal::HWDisplayId getDisplayId() const { return mDisplay.getId(); }
+        hal::HWConfigId getId() const { return mId; }
 
         int32_t getWidth() const { return mWidth; }
         int32_t getHeight() const { return mHeight; }
@@ -148,10 +141,10 @@
         int32_t getConfigGroup() const { return mConfigGroup; }
 
     private:
-        Config(Display& display, hwc2_config_t id);
+        Config(Display& display, hal::HWConfigId id);
 
         Display& mDisplay;
-        hwc2_config_t mId;
+        hal::HWConfigId mId;
 
         int32_t mWidth;
         int32_t mHeight;
@@ -161,168 +154,173 @@
         int32_t mConfigGroup;
     };
 
-    virtual hwc2_display_t getId() const = 0;
+    virtual hal::HWDisplayId getId() const = 0;
     virtual bool isConnected() const = 0;
     virtual void setConnected(bool connected) = 0; // For use by Device only
-    virtual const std::unordered_set<DisplayCapability>& getCapabilities() const = 0;
+    virtual const std::unordered_set<hal::DisplayCapability>& getCapabilities() const = 0;
     virtual bool isVsyncPeriodSwitchSupported() const = 0;
 
-    [[clang::warn_unused_result]] virtual Error acceptChanges() = 0;
-    [[clang::warn_unused_result]] virtual Error createLayer(Layer** outLayer) = 0;
-    [[clang::warn_unused_result]] virtual Error destroyLayer(Layer* layer) = 0;
-    [[clang::warn_unused_result]] virtual Error getActiveConfig(
+    [[clang::warn_unused_result]] virtual hal::Error acceptChanges() = 0;
+    [[clang::warn_unused_result]] virtual hal::Error createLayer(Layer** outLayer) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error destroyLayer(Layer* layer) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error getActiveConfig(
             std::shared_ptr<const Config>* outConfig) const = 0;
-    [[clang::warn_unused_result]] virtual Error getActiveConfigIndex(int* outIndex) const = 0;
-    [[clang::warn_unused_result]] virtual Error getChangedCompositionTypes(
-            std::unordered_map<Layer*, Composition>* outTypes) = 0;
-    [[clang::warn_unused_result]] virtual Error getColorModes(
-            std::vector<android::ui::ColorMode>* outModes) const = 0;
+    [[clang::warn_unused_result]] virtual hal::Error getActiveConfigIndex(int* outIndex) const = 0;
+    [[clang::warn_unused_result]] virtual hal::Error getChangedCompositionTypes(
+            std::unordered_map<Layer*, hal::Composition>* outTypes) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error getColorModes(
+            std::vector<hal::ColorMode>* outModes) const = 0;
     // Returns a bitmask which contains HdrMetadata::Type::*.
     [[clang::warn_unused_result]] virtual int32_t getSupportedPerFrameMetadata() const = 0;
-    [[clang::warn_unused_result]] virtual Error getRenderIntents(
-            android::ui::ColorMode colorMode,
-            std::vector<android::ui::RenderIntent>* outRenderIntents) const = 0;
-    [[clang::warn_unused_result]] virtual Error getDataspaceSaturationMatrix(
-            android::ui::Dataspace dataspace, android::mat4* outMatrix) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error getRenderIntents(
+            hal::ColorMode colorMode, std::vector<hal::RenderIntent>* outRenderIntents) const = 0;
+    [[clang::warn_unused_result]] virtual hal::Error getDataspaceSaturationMatrix(
+            hal::Dataspace dataspace, android::mat4* outMatrix) = 0;
 
-    // Doesn't call into the HWC2 device, so no Errors are possible
-    virtual std::vector<std::shared_ptr<const Config>> getConfigs() const = 0;
+    // Doesn't call into the HWC2 device, so no errors are possible
+    [[clang::warn_unused_result]] virtual std::vector<std::shared_ptr<const Config>> getConfigs()
+            const = 0;
 
-    [[clang::warn_unused_result]] virtual Error getName(std::string* outName) const = 0;
-    [[clang::warn_unused_result]] virtual Error getRequests(
-            DisplayRequest* outDisplayRequests,
-            std::unordered_map<Layer*, LayerRequest>* outLayerRequests) = 0;
-    [[clang::warn_unused_result]] virtual Error getConnectionType(
+    [[clang::warn_unused_result]] virtual hal::Error getName(std::string* outName) const = 0;
+    [[clang::warn_unused_result]] virtual hal::Error getRequests(
+            hal::DisplayRequest* outDisplayRequests,
+            std::unordered_map<Layer*, hal::LayerRequest>* outLayerRequests) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error getConnectionType(
             android::DisplayConnectionType*) const = 0;
-    [[clang::warn_unused_result]] virtual Error supportsDoze(bool* outSupport) const = 0;
-    [[clang::warn_unused_result]] virtual Error getHdrCapabilities(
+    [[clang::warn_unused_result]] virtual hal::Error supportsDoze(bool* outSupport) const = 0;
+    [[clang::warn_unused_result]] virtual hal::Error getHdrCapabilities(
             android::HdrCapabilities* outCapabilities) const = 0;
-    [[clang::warn_unused_result]] virtual Error getDisplayedContentSamplingAttributes(
-            android::ui::PixelFormat* outFormat, android::ui::Dataspace* outDataspace,
+    [[clang::warn_unused_result]] virtual hal::Error getDisplayedContentSamplingAttributes(
+            hal::PixelFormat* outFormat, hal::Dataspace* outDataspace,
             uint8_t* outComponentMask) const = 0;
-    [[clang::warn_unused_result]] virtual Error setDisplayContentSamplingEnabled(
+    [[clang::warn_unused_result]] virtual hal::Error setDisplayContentSamplingEnabled(
             bool enabled, uint8_t componentMask, uint64_t maxFrames) const = 0;
-    [[clang::warn_unused_result]] virtual Error getDisplayedContentSample(
+    [[clang::warn_unused_result]] virtual hal::Error getDisplayedContentSample(
             uint64_t maxFrames, uint64_t timestamp,
             android::DisplayedFrameStats* outStats) const = 0;
-    [[clang::warn_unused_result]] virtual Error getReleaseFences(
+    [[clang::warn_unused_result]] virtual hal::Error getReleaseFences(
             std::unordered_map<Layer*, android::sp<android::Fence>>* outFences) const = 0;
-    [[clang::warn_unused_result]] virtual Error present(
+    [[clang::warn_unused_result]] virtual hal::Error present(
             android::sp<android::Fence>* outPresentFence) = 0;
-    [[clang::warn_unused_result]] virtual Error setActiveConfig(
+    [[clang::warn_unused_result]] virtual hal::Error setActiveConfig(
             const std::shared_ptr<const Config>& config) = 0;
-    [[clang::warn_unused_result]] virtual Error setClientTarget(
+    [[clang::warn_unused_result]] virtual hal::Error setClientTarget(
             uint32_t slot, const android::sp<android::GraphicBuffer>& target,
-            const android::sp<android::Fence>& acquireFence, android::ui::Dataspace dataspace) = 0;
-    [[clang::warn_unused_result]] virtual Error setColorMode(
-            android::ui::ColorMode mode, android::ui::RenderIntent renderIntent) = 0;
-    [[clang::warn_unused_result]] virtual Error setColorTransform(
-            const android::mat4& matrix, android_color_transform_t hint) = 0;
-    [[clang::warn_unused_result]] virtual Error setOutputBuffer(
+            const android::sp<android::Fence>& acquireFence, hal::Dataspace dataspace) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setColorMode(
+            hal::ColorMode mode, hal::RenderIntent renderIntent) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setColorTransform(
+            const android::mat4& matrix, hal::ColorTransform hint) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setOutputBuffer(
             const android::sp<android::GraphicBuffer>& buffer,
             const android::sp<android::Fence>& releaseFence) = 0;
-    [[clang::warn_unused_result]] virtual Error setPowerMode(PowerMode mode) = 0;
-    [[clang::warn_unused_result]] virtual Error setVsyncEnabled(Vsync enabled) = 0;
-    [[clang::warn_unused_result]] virtual Error validate(uint32_t* outNumTypes,
-                                                         uint32_t* outNumRequests) = 0;
-    [[clang::warn_unused_result]] virtual Error presentOrValidate(
+    [[clang::warn_unused_result]] virtual hal::Error setPowerMode(hal::PowerMode mode) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setVsyncEnabled(hal::Vsync enabled) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error validate(uint32_t* outNumTypes,
+                                                              uint32_t* outNumRequests) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error presentOrValidate(
             uint32_t* outNumTypes, uint32_t* outNumRequests,
             android::sp<android::Fence>* outPresentFence, uint32_t* state) = 0;
-    [[clang::warn_unused_result]] virtual Error setDisplayBrightness(float brightness) const = 0;
-    [[clang::warn_unused_result]] virtual Error getDisplayVsyncPeriod(
+    [[clang::warn_unused_result]] virtual hal::Error setDisplayBrightness(
+            float brightness) const = 0;
+    [[clang::warn_unused_result]] virtual hal::Error getDisplayVsyncPeriod(
             nsecs_t* outVsyncPeriod) const = 0;
-    [[clang::warn_unused_result]] virtual Error setActiveConfigWithConstraints(
+    [[clang::warn_unused_result]] virtual hal::Error setActiveConfigWithConstraints(
             const std::shared_ptr<const HWC2::Display::Config>& config,
-            const VsyncPeriodChangeConstraints& constraints,
-            VsyncPeriodChangeTimeline* outTimeline) = 0;
-    [[clang::warn_unused_result]] virtual Error setAutoLowLatencyMode(bool on) const = 0;
-    [[clang::warn_unused_result]] virtual Error getSupportedContentTypes(
-            std::vector<HWC2::ContentType>*) const = 0;
-    [[clang::warn_unused_result]] virtual Error setContentType(HWC2::ContentType) const = 0;
+            const hal::VsyncPeriodChangeConstraints& constraints,
+            hal::VsyncPeriodChangeTimeline* outTimeline) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setAutoLowLatencyMode(bool on) const = 0;
+    [[clang::warn_unused_result]] virtual hal::Error getSupportedContentTypes(
+            std::vector<hal::ContentType>*) const = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setContentType(hal::ContentType) const = 0;
 };
 
 namespace impl {
 
 class Display : public HWC2::Display {
 public:
-    Display(android::Hwc2::Composer& composer, const std::unordered_set<Capability>& capabilities,
-            hwc2_display_t id, DisplayType type);
+    Display(android::Hwc2::Composer& composer,
+            const std::unordered_set<hal::Capability>& capabilities, hal::HWDisplayId id,
+            hal::DisplayType type);
     ~Display() override;
 
     // Required by HWC2
-    Error acceptChanges() override;
-    Error createLayer(Layer** outLayer) override;
-    Error destroyLayer(Layer* layer) override;
-    Error getActiveConfig(std::shared_ptr<const Config>* outConfig) const override;
-    Error getActiveConfigIndex(int* outIndex) const override;
-    Error getChangedCompositionTypes(std::unordered_map<Layer*, Composition>* outTypes) override;
-    Error getColorModes(std::vector<android::ui::ColorMode>* outModes) const override;
+    hal::Error acceptChanges() override;
+    hal::Error createLayer(Layer** outLayer) override;
+    hal::Error destroyLayer(Layer* layer) override;
+    hal::Error getActiveConfig(std::shared_ptr<const Config>* outConfig) const override;
+    hal::Error getActiveConfigIndex(int* outIndex) const override;
+    hal::Error getChangedCompositionTypes(
+            std::unordered_map<Layer*, hal::Composition>* outTypes) override;
+    hal::Error getColorModes(std::vector<hal::ColorMode>* outModes) const override;
     // Returns a bitmask which contains HdrMetadata::Type::*.
     int32_t getSupportedPerFrameMetadata() const override;
-    Error getRenderIntents(android::ui::ColorMode colorMode,
-                           std::vector<android::ui::RenderIntent>* outRenderIntents) const override;
-    Error getDataspaceSaturationMatrix(android::ui::Dataspace dataspace,
-                                       android::mat4* outMatrix) override;
+    hal::Error getRenderIntents(hal::ColorMode colorMode,
+                                std::vector<hal::RenderIntent>* outRenderIntents) const override;
+    hal::Error getDataspaceSaturationMatrix(hal::Dataspace dataspace,
+                                            android::mat4* outMatrix) override;
 
     // Doesn't call into the HWC2 device, so no errors are possible
     std::vector<std::shared_ptr<const Config>> getConfigs() const override;
 
-    Error getName(std::string* outName) const override;
-    Error getRequests(DisplayRequest* outDisplayRequests,
-                      std::unordered_map<Layer*, LayerRequest>* outLayerRequests) override;
-    Error getConnectionType(android::DisplayConnectionType*) const override;
-    Error supportsDoze(bool* outSupport) const override;
-    Error getHdrCapabilities(android::HdrCapabilities* outCapabilities) const override;
-    Error getDisplayedContentSamplingAttributes(android::ui::PixelFormat* outFormat,
-                                                android::ui::Dataspace* outDataspace,
-                                                uint8_t* outComponentMask) const override;
-    Error setDisplayContentSamplingEnabled(bool enabled, uint8_t componentMask,
-                                           uint64_t maxFrames) const override;
-    Error getDisplayedContentSample(uint64_t maxFrames, uint64_t timestamp,
-                                    android::DisplayedFrameStats* outStats) const override;
-    Error getReleaseFences(
+    hal::Error getName(std::string* outName) const override;
+    hal::Error getRequests(
+            hal::DisplayRequest* outDisplayRequests,
+            std::unordered_map<Layer*, hal::LayerRequest>* outLayerRequests) override;
+    hal::Error getConnectionType(android::DisplayConnectionType*) const override;
+    hal::Error supportsDoze(bool* outSupport) const override;
+    hal::Error getHdrCapabilities(android::HdrCapabilities* outCapabilities) const override;
+    hal::Error getDisplayedContentSamplingAttributes(hal::PixelFormat* outFormat,
+                                                     hal::Dataspace* outDataspace,
+                                                     uint8_t* outComponentMask) const override;
+    hal::Error setDisplayContentSamplingEnabled(bool enabled, uint8_t componentMask,
+                                                uint64_t maxFrames) const override;
+    hal::Error getDisplayedContentSample(uint64_t maxFrames, uint64_t timestamp,
+                                         android::DisplayedFrameStats* outStats) const override;
+    hal::Error getReleaseFences(
             std::unordered_map<Layer*, android::sp<android::Fence>>* outFences) const override;
-    Error present(android::sp<android::Fence>* outPresentFence) override;
-    Error setActiveConfig(const std::shared_ptr<const HWC2::Display::Config>& config) override;
-    Error setClientTarget(uint32_t slot, const android::sp<android::GraphicBuffer>& target,
-                          const android::sp<android::Fence>& acquireFence,
-                          android::ui::Dataspace dataspace) override;
-    Error setColorMode(android::ui::ColorMode mode,
-                       android::ui::RenderIntent renderIntent) override;
-    Error setColorTransform(const android::mat4& matrix, android_color_transform_t hint) override;
-    Error setOutputBuffer(const android::sp<android::GraphicBuffer>& buffer,
-                          const android::sp<android::Fence>& releaseFence) override;
-    Error setPowerMode(PowerMode mode) override;
-    Error setVsyncEnabled(Vsync enabled) override;
-    Error validate(uint32_t* outNumTypes, uint32_t* outNumRequests) override;
-    Error presentOrValidate(uint32_t* outNumTypes, uint32_t* outNumRequests,
-                            android::sp<android::Fence>* outPresentFence, uint32_t* state) override;
-    Error setDisplayBrightness(float brightness) const override;
-    Error getDisplayVsyncPeriod(nsecs_t* outVsyncPeriod) const override;
-    Error setActiveConfigWithConstraints(const std::shared_ptr<const HWC2::Display::Config>& config,
-                                         const VsyncPeriodChangeConstraints& constraints,
-                                         VsyncPeriodChangeTimeline* outTimeline) override;
-    Error setAutoLowLatencyMode(bool on) const override;
-    Error getSupportedContentTypes(
-            std::vector<HWC2::ContentType>* outSupportedContentTypes) const override;
-    Error setContentType(HWC2::ContentType contentType) const override;
+    hal::Error present(android::sp<android::Fence>* outPresentFence) override;
+    hal::Error setActiveConfig(const std::shared_ptr<const HWC2::Display::Config>& config) override;
+    hal::Error setClientTarget(uint32_t slot, const android::sp<android::GraphicBuffer>& target,
+                               const android::sp<android::Fence>& acquireFence,
+                               hal::Dataspace dataspace) override;
+    hal::Error setColorMode(hal::ColorMode mode, hal::RenderIntent renderIntent) override;
+    hal::Error setColorTransform(const android::mat4& matrix, hal::ColorTransform hint) override;
+    hal::Error setOutputBuffer(const android::sp<android::GraphicBuffer>& buffer,
+                               const android::sp<android::Fence>& releaseFence) override;
+    hal::Error setPowerMode(hal::PowerMode mode) override;
+    hal::Error setVsyncEnabled(hal::Vsync enabled) override;
+    hal::Error validate(uint32_t* outNumTypes, uint32_t* outNumRequests) override;
+    hal::Error presentOrValidate(uint32_t* outNumTypes, uint32_t* outNumRequests,
+                                 android::sp<android::Fence>* outPresentFence,
+                                 uint32_t* state) override;
+    hal::Error setDisplayBrightness(float brightness) const override;
+    hal::Error getDisplayVsyncPeriod(nsecs_t* outVsyncPeriod) const override;
+    hal::Error setActiveConfigWithConstraints(
+            const std::shared_ptr<const HWC2::Display::Config>& config,
+            const hal::VsyncPeriodChangeConstraints& constraints,
+            hal::VsyncPeriodChangeTimeline* outTimeline) override;
+    hal::Error setAutoLowLatencyMode(bool on) const override;
+    hal::Error getSupportedContentTypes(
+            std::vector<hal::ContentType>* outSupportedContentTypes) const override;
+    hal::Error setContentType(hal::ContentType contentType) const override;
     // Other Display methods
-    hwc2_display_t getId() const override { return mId; }
+    hal::HWDisplayId getId() const override { return mId; }
     bool isConnected() const override { return mIsConnected; }
     void setConnected(bool connected) override; // For use by Device only
-    const std::unordered_set<DisplayCapability>& getCapabilities() const override {
+    const std::unordered_set<hal::DisplayCapability>& getCapabilities() const override {
         return mDisplayCapabilities;
     };
     virtual bool isVsyncPeriodSwitchSupported() const override;
 
 private:
-    int32_t getAttribute(hwc2_config_t configId, Attribute attribute);
-    void loadConfig(hwc2_config_t configId);
+    int32_t getAttribute(hal::HWConfigId configId, hal::Attribute attribute);
+    void loadConfig(hal::HWConfigId configId);
     void loadConfigs();
 
     // This may fail (and return a null pointer) if no layer with this ID exists
     // on this display
-    Layer* getLayerById(hwc2_layer_t id) const;
+    Layer* getLayerById(hal::HWLayerId id) const;
 
     friend android::TestableSurfaceFlinger;
 
@@ -332,17 +330,17 @@
     // this HWC2::Display, so these references are guaranteed to be valid for
     // the lifetime of this object.
     android::Hwc2::Composer& mComposer;
-    const std::unordered_set<Capability>& mCapabilities;
+    const std::unordered_set<hal::Capability>& mCapabilities;
 
-    const hwc2_display_t mId;
-    DisplayType mType;
+    const hal::HWDisplayId mId;
+    hal::DisplayType mType;
     bool mIsConnected = false;
 
-    std::unordered_map<hwc2_layer_t, std::unique_ptr<Layer>> mLayers;
-    std::unordered_map<hwc2_config_t, std::shared_ptr<const Config>> mConfigs;
+    std::unordered_map<hal::HWLayerId, std::unique_ptr<Layer>> mLayers;
+    std::unordered_map<hal::HWConfigId, std::shared_ptr<const Config>> mConfigs;
 
     std::once_flag mDisplayCapabilityQueryFlag;
-    std::unordered_set<DisplayCapability> mDisplayCapabilities;
+    std::unordered_set<hal::DisplayCapability> mDisplayCapabilities;
 };
 
 } // namespace impl
@@ -351,99 +349,105 @@
 public:
     virtual ~Layer();
 
-    virtual hwc2_layer_t getId() const = 0;
+    virtual hal::HWLayerId getId() const = 0;
 
-    [[clang::warn_unused_result]] virtual Error setCursorPosition(int32_t x, int32_t y) = 0;
-    [[clang::warn_unused_result]] virtual Error setBuffer(
+    [[clang::warn_unused_result]] virtual hal::Error setCursorPosition(int32_t x, int32_t y) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setBuffer(
             uint32_t slot, const android::sp<android::GraphicBuffer>& buffer,
             const android::sp<android::Fence>& acquireFence) = 0;
-    [[clang::warn_unused_result]] virtual Error setSurfaceDamage(const android::Region& damage) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setSurfaceDamage(
+            const android::Region& damage) = 0;
 
-    [[clang::warn_unused_result]] virtual Error setBlendMode(BlendMode mode) = 0;
-    [[clang::warn_unused_result]] virtual Error setColor(hwc_color_t color) = 0;
-    [[clang::warn_unused_result]] virtual Error setCompositionType(Composition type) = 0;
-    [[clang::warn_unused_result]] virtual Error setDataspace(android::ui::Dataspace dataspace) = 0;
-    [[clang::warn_unused_result]] virtual Error setPerFrameMetadata(
+    [[clang::warn_unused_result]] virtual hal::Error setBlendMode(hal::BlendMode mode) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setColor(hal::Color color) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setCompositionType(hal::Composition type) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setDataspace(hal::Dataspace dataspace) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setPerFrameMetadata(
             const int32_t supportedPerFrameMetadata, const android::HdrMetadata& metadata) = 0;
-    [[clang::warn_unused_result]] virtual Error setDisplayFrame(const android::Rect& frame) = 0;
-    [[clang::warn_unused_result]] virtual Error setPlaneAlpha(float alpha) = 0;
-    [[clang::warn_unused_result]] virtual Error setSidebandStream(
+    [[clang::warn_unused_result]] virtual hal::Error setDisplayFrame(
+            const android::Rect& frame) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setPlaneAlpha(float alpha) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setSidebandStream(
             const native_handle_t* stream) = 0;
-    [[clang::warn_unused_result]] virtual Error setSourceCrop(const android::FloatRect& crop) = 0;
-    [[clang::warn_unused_result]] virtual Error setTransform(Transform transform) = 0;
-    [[clang::warn_unused_result]] virtual Error setVisibleRegion(const android::Region& region) = 0;
-    [[clang::warn_unused_result]] virtual Error setZOrder(uint32_t z) = 0;
-    [[clang::warn_unused_result]] virtual Error setInfo(uint32_t type, uint32_t appId) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setSourceCrop(
+            const android::FloatRect& crop) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setTransform(hal::Transform transform) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setVisibleRegion(
+            const android::Region& region) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setZOrder(uint32_t z) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setInfo(uint32_t type, uint32_t appId) = 0;
 
     // Composer HAL 2.3
-    [[clang::warn_unused_result]] virtual Error setColorTransform(const android::mat4& matrix) = 0;
+    [[clang::warn_unused_result]] virtual hal::Error setColorTransform(
+            const android::mat4& matrix) = 0;
 
     // Composer HAL 2.4
-    [[clang::warn_unused_result]] virtual Error setLayerGenericMetadata(
+    [[clang::warn_unused_result]] virtual hal::Error setLayerGenericMetadata(
             const std::string& name, bool mandatory, const std::vector<uint8_t>& value) = 0;
 };
 
 namespace impl {
 
-// Convenience C++ class to access hwc2_device_t Layer functions directly.
+// Convenience C++ class to access per layer functions directly.
 
 class Layer : public HWC2::Layer {
 public:
-    Layer(android::Hwc2::Composer& composer, const std::unordered_set<Capability>& capabilities,
-          hwc2_display_t displayId, hwc2_layer_t layerId);
+    Layer(android::Hwc2::Composer& composer,
+          const std::unordered_set<hal::Capability>& capabilities, hal::HWDisplayId displayId,
+          hal::HWLayerId layerId);
     ~Layer() override;
 
-    hwc2_layer_t getId() const override { return mId; }
+    hal::HWLayerId getId() const override { return mId; }
 
-    Error setCursorPosition(int32_t x, int32_t y) override;
-    Error setBuffer(uint32_t slot, const android::sp<android::GraphicBuffer>& buffer,
-                    const android::sp<android::Fence>& acquireFence) override;
-    Error setSurfaceDamage(const android::Region& damage) override;
+    hal::Error setCursorPosition(int32_t x, int32_t y) override;
+    hal::Error setBuffer(uint32_t slot, const android::sp<android::GraphicBuffer>& buffer,
+                         const android::sp<android::Fence>& acquireFence) override;
+    hal::Error setSurfaceDamage(const android::Region& damage) override;
 
-    Error setBlendMode(BlendMode mode) override;
-    Error setColor(hwc_color_t color) override;
-    Error setCompositionType(Composition type) override;
-    Error setDataspace(android::ui::Dataspace dataspace) override;
-    Error setPerFrameMetadata(const int32_t supportedPerFrameMetadata,
-                              const android::HdrMetadata& metadata) override;
-    Error setDisplayFrame(const android::Rect& frame) override;
-    Error setPlaneAlpha(float alpha) override;
-    Error setSidebandStream(const native_handle_t* stream) override;
-    Error setSourceCrop(const android::FloatRect& crop) override;
-    Error setTransform(Transform transform) override;
-    Error setVisibleRegion(const android::Region& region) override;
-    Error setZOrder(uint32_t z) override;
-    Error setInfo(uint32_t type, uint32_t appId) override;
+    hal::Error setBlendMode(hal::BlendMode mode) override;
+    hal::Error setColor(hal::Color color) override;
+    hal::Error setCompositionType(hal::Composition type) override;
+    hal::Error setDataspace(hal::Dataspace dataspace) override;
+    hal::Error setPerFrameMetadata(const int32_t supportedPerFrameMetadata,
+                                   const android::HdrMetadata& metadata) override;
+    hal::Error setDisplayFrame(const android::Rect& frame) override;
+    hal::Error setPlaneAlpha(float alpha) override;
+    hal::Error setSidebandStream(const native_handle_t* stream) override;
+    hal::Error setSourceCrop(const android::FloatRect& crop) override;
+    hal::Error setTransform(hal::Transform transform) override;
+    hal::Error setVisibleRegion(const android::Region& region) override;
+    hal::Error setZOrder(uint32_t z) override;
+    hal::Error setInfo(uint32_t type, uint32_t appId) override;
 
     // Composer HAL 2.3
-    Error setColorTransform(const android::mat4& matrix) override;
+    hal::Error setColorTransform(const android::mat4& matrix) override;
 
     // Composer HAL 2.4
-    Error setLayerGenericMetadata(const std::string& name, bool mandatory,
-                                  const std::vector<uint8_t>& value) override;
+    hal::Error setLayerGenericMetadata(const std::string& name, bool mandatory,
+                                       const std::vector<uint8_t>& value) override;
 
 private:
     // These are references to data owned by HWC2::Device, which will outlive
     // this HWC2::Layer, so these references are guaranteed to be valid for
     // the lifetime of this object.
     android::Hwc2::Composer& mComposer;
-    const std::unordered_set<Capability>& mCapabilities;
+    const std::unordered_set<hal::Capability>& mCapabilities;
 
-    hwc2_display_t mDisplayId;
-    hwc2_layer_t mId;
+    hal::HWDisplayId mDisplayId;
+    hal::HWLayerId mId;
 
     // Cached HWC2 data, to ensure the same commands aren't sent to the HWC
     // multiple times.
     android::Region mVisibleRegion = android::Region::INVALID_REGION;
     android::Region mDamageRegion = android::Region::INVALID_REGION;
-    android::ui::Dataspace mDataSpace = android::ui::Dataspace::UNKNOWN;
+    hal::Dataspace mDataSpace = hal::Dataspace::UNKNOWN;
     android::HdrMetadata mHdrMetadata;
     android::mat4 mColorMatrix;
     uint32_t mBufferSlot;
 };
 
 } // namespace impl
-
 } // namespace HWC2
+} // namespace android
 
 #endif // ANDROID_SF_HWC2_H
diff --git a/services/surfaceflinger/DisplayHardware/HWComposer.cpp b/services/surfaceflinger/DisplayHardware/HWComposer.cpp
index f30d662..2f59469 100644
--- a/services/surfaceflinger/DisplayHardware/HWComposer.cpp
+++ b/services/surfaceflinger/DisplayHardware/HWComposer.cpp
@@ -60,7 +60,7 @@
 
 #define RETURN_IF_HWC_ERROR_FOR(what, error, displayId, ...) \
     do {                                                     \
-        if (error != HWC2::Error::None) {                    \
+        if (error != hal::Error::NONE) {                     \
             LOG_HWC_ERROR(what, error, displayId);           \
             return __VA_ARGS__;                              \
         }                                                    \
@@ -69,34 +69,34 @@
 #define RETURN_IF_HWC_ERROR(error, displayId, ...) \
     RETURN_IF_HWC_ERROR_FOR(__FUNCTION__, error, displayId, __VA_ARGS__)
 
+namespace hal = android::hardware::graphics::composer::hal;
+
 namespace {
 
 using android::hardware::Return;
 using android::hardware::Void;
+using android::HWC2::ComposerCallback;
 
-class ComposerCallbackBridge : public android::Hwc2::IComposerCallback {
+class ComposerCallbackBridge : public hal::IComposerCallback {
 public:
-    ComposerCallbackBridge(HWC2::ComposerCallback* callback, int32_t sequenceId,
+    ComposerCallbackBridge(ComposerCallback* callback, int32_t sequenceId,
                            bool vsyncSwitchingSupported)
           : mCallback(callback),
             mSequenceId(sequenceId),
             mVsyncSwitchingSupported(vsyncSwitchingSupported) {}
 
-    android::hardware::Return<void> onHotplug(
-            android::Hwc2::Display display,
-            android::Hwc2::IComposerCallback::Connection conn) override {
-        HWC2::Connection connection = static_cast<HWC2::Connection>(conn);
-        mCallback->onHotplugReceived(mSequenceId, display, connection);
+    android::hardware::Return<void> onHotplug(hal::HWDisplayId display,
+                                              hal::Connection conn) override {
+        mCallback->onHotplugReceived(mSequenceId, display, conn);
         return android::hardware::Void();
     }
 
-    android::hardware::Return<void> onRefresh(android::Hwc2::Display display) override {
+    android::hardware::Return<void> onRefresh(hal::HWDisplayId display) override {
         mCallback->onRefreshReceived(mSequenceId, display);
         return android::hardware::Void();
     }
 
-    android::hardware::Return<void> onVsync(android::Hwc2::Display display,
-                                            int64_t timestamp) override {
+    android::hardware::Return<void> onVsync(hal::HWDisplayId display, int64_t timestamp) override {
         if (!mVsyncSwitchingSupported) {
             mCallback->onVsyncReceived(mSequenceId, display, timestamp, std::nullopt);
         } else {
@@ -105,9 +105,8 @@
         return android::hardware::Void();
     }
 
-    android::hardware::Return<void> onVsync_2_4(
-            android::Hwc2::Display display, int64_t timestamp,
-            android::Hwc2::VsyncPeriodNanos vsyncPeriodNanos) override {
+    android::hardware::Return<void> onVsync_2_4(hal::HWDisplayId display, int64_t timestamp,
+                                                hal::VsyncPeriodNanos vsyncPeriodNanos) override {
         if (mVsyncSwitchingSupported) {
             mCallback->onVsyncReceived(mSequenceId, display, timestamp,
                                        std::make_optional(vsyncPeriodNanos));
@@ -118,23 +117,19 @@
     }
 
     android::hardware::Return<void> onVsyncPeriodTimingChanged(
-            android::Hwc2::Display display,
-            const android::Hwc2::VsyncPeriodChangeTimeline& updatedTimeline) override {
-        hwc_vsync_period_change_timeline_t timeline;
-        timeline.newVsyncAppliedTimeNanos = updatedTimeline.newVsyncAppliedTimeNanos;
-        timeline.refreshRequired = updatedTimeline.refreshRequired;
-        timeline.refreshTimeNanos = updatedTimeline.refreshTimeNanos;
-        mCallback->onVsyncPeriodTimingChangedReceived(mSequenceId, display, timeline);
+            hal::HWDisplayId display,
+            const hal::VsyncPeriodChangeTimeline& updatedTimeline) override {
+        mCallback->onVsyncPeriodTimingChangedReceived(mSequenceId, display, updatedTimeline);
         return android::hardware::Void();
     }
 
-    android::hardware::Return<void> onSeamlessPossible(android::Hwc2::Display display) override {
+    android::hardware::Return<void> onSeamlessPossible(hal::HWDisplayId display) override {
         mCallback->onSeamlessPossible(mSequenceId, display);
         return android::hardware::Void();
     }
 
 private:
-    HWC2::ComposerCallback* mCallback;
+    ComposerCallback* mCallback;
     const int32_t mSequenceId;
     const bool mVsyncSwitchingSupported;
 };
@@ -173,12 +168,12 @@
     mComposer->registerCallback(callbackBridge);
 }
 
-bool HWComposer::getDisplayIdentificationData(hwc2_display_t hwcDisplayId, uint8_t* outPort,
+bool HWComposer::getDisplayIdentificationData(hal::HWDisplayId hwcDisplayId, uint8_t* outPort,
                                               DisplayIdentificationData* outData) const {
-    const auto error = static_cast<HWC2::Error>(
+    const auto error = static_cast<hal::Error>(
             mComposer->getDisplayIdentificationData(hwcDisplayId, outPort, outData));
-    if (error != HWC2::Error::None) {
-        if (error != HWC2::Error::Unsupported) {
+    if (error != hal::Error::NONE) {
+        if (error != hal::Error::UNSUPPORTED) {
             LOG_HWC_DISPLAY_ERROR(hwcDisplayId, to_string(error).c_str());
         }
         return false;
@@ -186,29 +181,29 @@
     return true;
 }
 
-bool HWComposer::hasCapability(HWC2::Capability capability) const {
+bool HWComposer::hasCapability(hal::Capability capability) const {
     return mCapabilities.count(capability) > 0;
 }
 
 bool HWComposer::hasDisplayCapability(DisplayId displayId,
-                                      HWC2::DisplayCapability capability) const {
+                                      hal::DisplayCapability capability) const {
     RETURN_IF_INVALID_DISPLAY(displayId, false);
     return mDisplayData.at(displayId).hwcDisplay->getCapabilities().count(capability) > 0;
 }
 
-std::optional<DisplayIdentificationInfo> HWComposer::onHotplug(hwc2_display_t hwcDisplayId,
-                                                               HWC2::Connection connection) {
+std::optional<DisplayIdentificationInfo> HWComposer::onHotplug(hal::HWDisplayId hwcDisplayId,
+                                                               hal::Connection connection) {
     switch (connection) {
-        case HWC2::Connection::Connected:
+        case hal::Connection::CONNECTED:
             return onHotplugConnect(hwcDisplayId);
-        case HWC2::Connection::Disconnected:
+        case hal::Connection::DISCONNECTED:
             return onHotplugDisconnect(hwcDisplayId);
-        case HWC2::Connection::Invalid:
+        case hal::Connection::INVALID:
             return {};
     }
 }
 
-bool HWComposer::onVsync(hwc2_display_t hwcDisplayId, int64_t timestamp) {
+bool HWComposer::onVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp) {
     const auto displayId = toPhysicalDisplayId(hwcDisplayId);
     if (!displayId) {
         LOG_HWC_DISPLAY_ERROR(hwcDisplayId, "Invalid HWC display");
@@ -260,16 +255,16 @@
               height, SurfaceFlinger::maxVirtualDisplaySize);
         return {};
     }
-    hwc2_display_t hwcDisplayId = 0;
-    const auto error = static_cast<HWC2::Error>(
+    hal::HWDisplayId hwcDisplayId = 0;
+    const auto error = static_cast<hal::Error>(
             mComposer->createVirtualDisplay(width, height, format, &hwcDisplayId));
-    if (error != HWC2::Error::None) {
+    if (error != hal::Error::NONE) {
         ALOGE("%s: Failed to create HWC virtual display", __FUNCTION__);
         return {};
     }
 
     auto display = std::make_unique<HWC2::impl::Display>(*mComposer.get(), mCapabilities,
-                                                         hwcDisplayId, HWC2::DisplayType::Virtual);
+                                                         hwcDisplayId, hal::DisplayType::VIRTUAL);
     display->setConnected(true);
 
     DisplayId displayId;
@@ -288,7 +283,7 @@
     return displayId;
 }
 
-void HWComposer::allocatePhysicalDisplay(hwc2_display_t hwcDisplayId, DisplayId displayId) {
+void HWComposer::allocatePhysicalDisplay(hal::HWDisplayId hwcDisplayId, DisplayId displayId) {
     if (!mInternalHwcDisplayId) {
         mInternalHwcDisplayId = hwcDisplayId;
     } else if (mInternalHwcDisplayId != hwcDisplayId && !mExternalHwcDisplayId) {
@@ -298,7 +293,7 @@
     auto& displayData = mDisplayData[displayId];
     auto newDisplay =
             std::make_unique<HWC2::impl::Display>(*mComposer.get(), mCapabilities, hwcDisplayId,
-                                                  HWC2::DisplayType::Physical);
+                                                  hal::DisplayType::PHYSICAL);
     newDisplay->setConnected(true);
     displayData.hwcDisplay = std::move(newDisplay);
     mPhysicalDisplayIdMap[hwcDisplayId] = displayId;
@@ -357,7 +352,7 @@
 
     std::shared_ptr<const HWC2::Display::Config> config;
     auto error = mDisplayData.at(displayId).hwcDisplay->getActiveConfig(&config);
-    if (error == HWC2::Error::BadConfig) {
+    if (error == hal::Error::BAD_CONFIG) {
         LOG_DISPLAY_ERROR(displayId, "No active config");
         return nullptr;
     }
@@ -408,7 +403,7 @@
 
     int index;
     auto error = mDisplayData.at(displayId).hwcDisplay->getActiveConfigIndex(&index);
-    if (error == HWC2::Error::BadConfig) {
+    if (error == hal::Error::BAD_CONFIG) {
         LOG_DISPLAY_ERROR(displayId, "No active config");
         return -1;
     }
@@ -446,7 +441,7 @@
     return NO_ERROR;
 }
 
-void HWComposer::setVsyncEnabled(DisplayId displayId, HWC2::Vsync enabled) {
+void HWComposer::setVsyncEnabled(DisplayId displayId, hal::Vsync enabled) {
     RETURN_IF_INVALID_DISPLAY(displayId);
     auto& displayData = mDisplayData[displayId];
 
@@ -471,7 +466,7 @@
     displayData.vsyncEnabled = enabled;
 
     const auto tag = "HW_VSYNC_ON_" + to_string(displayId);
-    ATRACE_INT(tag.c_str(), enabled == HWC2::Vsync::Enable ? 1 : 0);
+    ATRACE_INT(tag.c_str(), enabled == hal::Vsync::ENABLE ? 1 : 0);
 }
 
 status_t HWComposer::setClientTarget(DisplayId displayId, uint32_t slot,
@@ -502,7 +497,7 @@
     uint32_t numTypes = 0;
     uint32_t numRequests = 0;
 
-    HWC2::Error error = HWC2::Error::None;
+    hal::Error error = hal::Error::NONE;
 
     // First try to skip validate altogether when there is no client
     // composition.  When there is client composition, since we haven't
@@ -513,7 +508,7 @@
         sp<Fence> outPresentFence;
         uint32_t state = UINT32_MAX;
         error = hwcDisplay->presentOrValidate(&numTypes, &numRequests, &outPresentFence , &state);
-        if (error != HWC2::Error::HasChanges) {
+        if (!hasChangesError(error)) {
             RETURN_IF_HWC_ERROR_FOR("presentOrValidate", error, displayId, UNKNOWN_ERROR);
         }
         if (state == 1) { //Present Succeeded.
@@ -530,7 +525,7 @@
         error = hwcDisplay->validate(&numTypes, &numRequests);
     }
     ALOGV("SkipValidate failed, Falling back to SLOW validate/present");
-    if (error != HWC2::Error::HasChanges) {
+    if (!hasChangesError(error)) {
         RETURN_IF_HWC_ERROR_FOR("validate", error, displayId, BAD_INDEX);
     }
 
@@ -539,7 +534,7 @@
     error = hwcDisplay->getChangedCompositionTypes(&changedTypes);
     RETURN_IF_HWC_ERROR_FOR("getChangedCompositionTypes", error, displayId, BAD_INDEX);
 
-    auto displayRequests = static_cast<HWC2::DisplayRequest>(0);
+    auto displayRequests = static_cast<hal::DisplayRequest>(0);
     android::HWComposer::DeviceRequestedChanges::LayerRequests layerRequests;
     layerRequests.reserve(numRequests);
     error = hwcDisplay->getRequests(&displayRequests, &layerRequests);
@@ -580,7 +575,7 @@
 
     if (displayData.validateWasSkipped) {
         // explicitly flush all pending commands
-        auto error = static_cast<HWC2::Error>(mComposer->executeCommands());
+        auto error = static_cast<hal::Error>(mComposer->executeCommands());
         RETURN_IF_HWC_ERROR_FOR("executeCommands", error, displayId, UNKNOWN_ERROR);
         RETURN_IF_HWC_ERROR_FOR("present", displayData.presentError, displayId, UNKNOWN_ERROR);
         return NO_ERROR;
@@ -607,42 +602,42 @@
         return INVALID_OPERATION;
     }
 
-    auto mode = static_cast<HWC2::PowerMode>(intMode);
-    if (mode == HWC2::PowerMode::Off) {
-        setVsyncEnabled(displayId, HWC2::Vsync::Disable);
+    auto mode = static_cast<hal::PowerMode>(intMode);
+    if (mode == hal::PowerMode::OFF) {
+        setVsyncEnabled(displayId, hal::Vsync::DISABLE);
     }
 
     auto& hwcDisplay = displayData.hwcDisplay;
     switch (mode) {
-        case HWC2::PowerMode::Off:
-        case HWC2::PowerMode::On:
+        case hal::PowerMode::OFF:
+        case hal::PowerMode::ON:
             ALOGV("setPowerMode: Calling HWC %s", to_string(mode).c_str());
             {
                 auto error = hwcDisplay->setPowerMode(mode);
-                if (error != HWC2::Error::None) {
-                    LOG_HWC_ERROR(("setPowerMode(" + to_string(mode) + ")").c_str(),
-                                  error, displayId);
+                if (error != hal::Error::NONE) {
+                    LOG_HWC_ERROR(("setPowerMode(" + to_string(mode) + ")").c_str(), error,
+                                  displayId);
                 }
             }
             break;
-        case HWC2::PowerMode::Doze:
-        case HWC2::PowerMode::DozeSuspend:
+        case hal::PowerMode::DOZE:
+        case hal::PowerMode::DOZE_SUSPEND:
             ALOGV("setPowerMode: Calling HWC %s", to_string(mode).c_str());
             {
                 bool supportsDoze = false;
                 auto error = hwcDisplay->supportsDoze(&supportsDoze);
-                if (error != HWC2::Error::None) {
+                if (error != hal::Error::NONE) {
                     LOG_HWC_ERROR("supportsDoze", error, displayId);
                 }
 
                 if (!supportsDoze) {
-                    mode = HWC2::PowerMode::On;
+                    mode = hal::PowerMode::ON;
                 }
 
                 error = hwcDisplay->setPowerMode(mode);
-                if (error != HWC2::Error::None) {
-                    LOG_HWC_ERROR(("setPowerMode(" + to_string(mode) + ")").c_str(),
-                                  error, displayId);
+                if (error != hal::Error::NONE) {
+                    LOG_HWC_ERROR(("setPowerMode(" + to_string(mode) + ")").c_str(), error,
+                                  displayId);
                 }
             }
             break;
@@ -655,8 +650,8 @@
 }
 
 status_t HWComposer::setActiveConfigWithConstraints(
-        DisplayId displayId, size_t configId, const HWC2::VsyncPeriodChangeConstraints& constraints,
-        HWC2::VsyncPeriodChangeTimeline* outTimeline) {
+        DisplayId displayId, size_t configId, const hal::VsyncPeriodChangeConstraints& constraints,
+        hal::VsyncPeriodChangeTimeline* outTimeline) {
     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
 
     auto& displayData = mDisplayData[displayId];
@@ -677,9 +672,10 @@
 
     auto& displayData = mDisplayData[displayId];
     bool isIdentity = transform == mat4();
-    auto error = displayData.hwcDisplay->setColorTransform(transform,
-            isIdentity ? HAL_COLOR_TRANSFORM_IDENTITY :
-            HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX);
+    auto error = displayData.hwcDisplay
+                         ->setColorTransform(transform,
+                                             isIdentity ? hal::ColorTransform::IDENTITY
+                                                        : hal::ColorTransform::ARBITRARY_MATRIX);
     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
     return NO_ERROR;
 }
@@ -770,7 +766,7 @@
             mDisplayData[displayId]
                     .hwcDisplay->getDisplayedContentSamplingAttributes(outFormat, outDataspace,
                                                                        outComponentMask);
-    if (error == HWC2::Error::Unsupported) RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
+    if (error == hal::Error::UNSUPPORTED) RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
     return NO_ERROR;
 }
@@ -783,8 +779,8 @@
                                                                                  componentMask,
                                                                                  maxFrames);
 
-    if (error == HWC2::Error::Unsupported) RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
-    if (error == HWC2::Error::BadParameter) RETURN_IF_HWC_ERROR(error, displayId, BAD_VALUE);
+    if (error == hal::Error::UNSUPPORTED) RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
+    if (error == hal::Error::BAD_PARAMETER) RETURN_IF_HWC_ERROR(error, displayId, BAD_VALUE);
     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
     return NO_ERROR;
 }
@@ -802,10 +798,10 @@
 status_t HWComposer::setDisplayBrightness(DisplayId displayId, float brightness) {
     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
     const auto error = mDisplayData[displayId].hwcDisplay->setDisplayBrightness(brightness);
-    if (error == HWC2::Error::Unsupported) {
+    if (error == hal::Error::UNSUPPORTED) {
         RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
     }
-    if (error == HWC2::Error::BadParameter) {
+    if (error == hal::Error::BAD_PARAMETER) {
         RETURN_IF_HWC_ERROR(error, displayId, BAD_VALUE);
     }
     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
@@ -819,10 +815,10 @@
 status_t HWComposer::setAutoLowLatencyMode(DisplayId displayId, bool on) {
     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
     const auto error = mDisplayData[displayId].hwcDisplay->setAutoLowLatencyMode(on);
-    if (error == HWC2::Error::Unsupported) {
+    if (error == hal::Error::UNSUPPORTED) {
         RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
     }
-    if (error == HWC2::Error::BadParameter) {
+    if (error == hal::Error::BAD_PARAMETER) {
         RETURN_IF_HWC_ERROR(error, displayId, BAD_VALUE);
     }
     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
@@ -830,7 +826,7 @@
 }
 
 status_t HWComposer::getSupportedContentTypes(
-        DisplayId displayId, std::vector<HWC2::ContentType>* outSupportedContentTypes) {
+        DisplayId displayId, std::vector<hal::ContentType>* outSupportedContentTypes) {
     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
     const auto error =
             mDisplayData[displayId].hwcDisplay->getSupportedContentTypes(outSupportedContentTypes);
@@ -840,13 +836,13 @@
     return NO_ERROR;
 }
 
-status_t HWComposer::setContentType(DisplayId displayId, HWC2::ContentType contentType) {
+status_t HWComposer::setContentType(DisplayId displayId, hal::ContentType contentType) {
     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
     const auto error = mDisplayData[displayId].hwcDisplay->setContentType(contentType);
-    if (error == HWC2::Error::Unsupported) {
+    if (error == hal::Error::UNSUPPORTED) {
         RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
     }
-    if (error == HWC2::Error::BadParameter) {
+    if (error == hal::Error::BAD_PARAMETER) {
         RETURN_IF_HWC_ERROR(error, displayId, BAD_VALUE);
     }
     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
@@ -862,7 +858,7 @@
     result.append(mComposer->dumpDebugInfo());
 }
 
-std::optional<DisplayId> HWComposer::toPhysicalDisplayId(hwc2_display_t hwcDisplayId) const {
+std::optional<DisplayId> HWComposer::toPhysicalDisplayId(hal::HWDisplayId hwcDisplayId) const {
     if (const auto it = mPhysicalDisplayIdMap.find(hwcDisplayId);
         it != mPhysicalDisplayIdMap.end()) {
         return it->second;
@@ -870,7 +866,7 @@
     return {};
 }
 
-std::optional<hwc2_display_t> HWComposer::fromPhysicalDisplayId(DisplayId displayId) const {
+std::optional<hal::HWDisplayId> HWComposer::fromPhysicalDisplayId(DisplayId displayId) const {
     if (const auto it = mDisplayData.find(displayId);
         it != mDisplayData.end() && !it->second.isVirtual) {
         return it->second.hwcDisplay->getId();
@@ -878,7 +874,7 @@
     return {};
 }
 
-bool HWComposer::shouldIgnoreHotplugConnect(hwc2_display_t hwcDisplayId,
+bool HWComposer::shouldIgnoreHotplugConnect(hal::HWDisplayId hwcDisplayId,
                                             bool hasDisplayIdentificationData) const {
     if (isUsingVrComposer() && mInternalHwcDisplayId) {
         ALOGE("Ignoring connection of external display %" PRIu64 " in VR mode", hwcDisplayId);
@@ -899,7 +895,8 @@
     return false;
 }
 
-std::optional<DisplayIdentificationInfo> HWComposer::onHotplugConnect(hwc2_display_t hwcDisplayId) {
+std::optional<DisplayIdentificationInfo> HWComposer::onHotplugConnect(
+        hal::HWDisplayId hwcDisplayId) {
     std::optional<DisplayIdentificationInfo> info;
     if (const auto displayId = toPhysicalDisplayId(hwcDisplayId)) {
         info = DisplayIdentificationInfo{.id = *displayId,
@@ -947,7 +944,7 @@
 }
 
 std::optional<DisplayIdentificationInfo> HWComposer::onHotplugDisconnect(
-        hwc2_display_t hwcDisplayId) {
+        hal::HWDisplayId hwcDisplayId) {
     const auto displayId = toPhysicalDisplayId(hwcDisplayId);
     if (!displayId) {
         ALOGE("Ignoring disconnection of invalid HWC display %" PRIu64, hwcDisplayId);
@@ -969,10 +966,10 @@
 }
 
 void HWComposer::loadCapabilities() {
-    static_assert(sizeof(HWC2::Capability) == sizeof(int32_t), "Capability size has changed");
+    static_assert(sizeof(hal::Capability) == sizeof(int32_t), "Capability size has changed");
     auto capabilities = mComposer->getCapabilities();
     for (auto capability : capabilities) {
-        mCapabilities.emplace(static_cast<HWC2::Capability>(capability));
+        mCapabilities.emplace(static_cast<hal::Capability>(capability));
     }
 }
 
diff --git a/services/surfaceflinger/DisplayHardware/HWComposer.h b/services/surfaceflinger/DisplayHardware/HWComposer.h
index e18419a..431b8e2 100644
--- a/services/surfaceflinger/DisplayHardware/HWComposer.h
+++ b/services/surfaceflinger/DisplayHardware/HWComposer.h
@@ -39,9 +39,12 @@
 
 #include "DisplayIdentification.h"
 #include "HWC2.h"
+#include "Hal.h"
 
 namespace android {
 
+namespace hal = hardware::graphics::composer::hal;
+
 struct DisplayedFrameStats;
 class GraphicBuffer;
 class TestableSurfaceFlinger;
@@ -66,18 +69,18 @@
 
     virtual void setConfiguration(HWC2::ComposerCallback* callback, int32_t sequenceId) = 0;
 
-    virtual bool getDisplayIdentificationData(hwc2_display_t hwcDisplayId, uint8_t* outPort,
+    virtual bool getDisplayIdentificationData(hal::HWDisplayId hwcDisplayId, uint8_t* outPort,
                                               DisplayIdentificationData* outData) const = 0;
 
-    virtual bool hasCapability(HWC2::Capability capability) const = 0;
+    virtual bool hasCapability(hal::Capability capability) const = 0;
     virtual bool hasDisplayCapability(DisplayId displayId,
-                                      HWC2::DisplayCapability capability) const = 0;
+                                      hal::DisplayCapability capability) const = 0;
 
     // Attempts to allocate a virtual display and returns its ID if created on the HWC device.
     virtual std::optional<DisplayId> allocateVirtualDisplay(uint32_t width, uint32_t height,
                                                             ui::PixelFormat* format) = 0;
 
-    virtual void allocatePhysicalDisplay(hwc2_display_t hwcDisplayId, DisplayId displayId) = 0;
+    virtual void allocatePhysicalDisplay(hal::HWDisplayId hwcDisplayId, DisplayId displayId) = 0;
 
     // Attempts to create a new layer on this display
     virtual HWC2::Layer* createLayer(DisplayId displayId) = 0;
@@ -85,9 +88,9 @@
     virtual void destroyLayer(DisplayId displayId, HWC2::Layer* layer) = 0;
 
     struct DeviceRequestedChanges {
-        using ChangedTypes = std::unordered_map<HWC2::Layer*, HWC2::Composition>;
-        using DisplayRequests = HWC2::DisplayRequest;
-        using LayerRequests = std::unordered_map<HWC2::Layer*, HWC2::LayerRequest>;
+        using ChangedTypes = std::unordered_map<HWC2::Layer*, hal::Composition>;
+        using DisplayRequests = hal::DisplayRequest;
+        using LayerRequests = std::unordered_map<HWC2::Layer*, hal::LayerRequest>;
 
         ChangedTypes changedTypes;
         DisplayRequests displayRequests;
@@ -167,11 +170,11 @@
     // Returns stable display ID (and display name on connection of new or previously disconnected
     // display), or std::nullopt if hotplug event was ignored.
     // This function is called from SurfaceFlinger.
-    virtual std::optional<DisplayIdentificationInfo> onHotplug(hwc2_display_t hwcDisplayId,
-                                                               HWC2::Connection connection) = 0;
+    virtual std::optional<DisplayIdentificationInfo> onHotplug(hal::HWDisplayId hwcDisplayId,
+                                                               hal::Connection connection) = 0;
 
-    virtual bool onVsync(hwc2_display_t hwcDisplayId, int64_t timestamp) = 0;
-    virtual void setVsyncEnabled(DisplayId displayId, HWC2::Vsync enabled) = 0;
+    virtual bool onVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp) = 0;
+    virtual void setVsyncEnabled(DisplayId displayId, hal::Vsync enabled) = 0;
 
     virtual nsecs_t getRefreshTimestamp(DisplayId displayId) const = 0;
     virtual bool isConnected(DisplayId displayId) const = 0;
@@ -197,12 +200,12 @@
     virtual nsecs_t getDisplayVsyncPeriod(DisplayId displayId) const = 0;
     virtual status_t setActiveConfigWithConstraints(
             DisplayId displayId, size_t configId,
-            const HWC2::VsyncPeriodChangeConstraints& constraints,
-            HWC2::VsyncPeriodChangeTimeline* outTimeline) = 0;
+            const hal::VsyncPeriodChangeConstraints& constraints,
+            hal::VsyncPeriodChangeTimeline* outTimeline) = 0;
     virtual status_t setAutoLowLatencyMode(DisplayId displayId, bool on) = 0;
     virtual status_t getSupportedContentTypes(
-            DisplayId displayId, std::vector<HWC2::ContentType>* outSupportedContentTypes) = 0;
-    virtual status_t setContentType(DisplayId displayId, HWC2::ContentType contentType) = 0;
+            DisplayId displayId, std::vector<hal::ContentType>* outSupportedContentTypes) = 0;
+    virtual status_t setContentType(DisplayId displayId, hal::ContentType contentType) = 0;
     virtual const std::unordered_map<std::string, bool>& getSupportedLayerGenericMetadata()
             const = 0;
 
@@ -212,11 +215,11 @@
     virtual Hwc2::Composer* getComposer() const = 0;
 
     // TODO(b/74619554): Remove special cases for internal/external display.
-    virtual std::optional<hwc2_display_t> getInternalHwcDisplayId() const = 0;
-    virtual std::optional<hwc2_display_t> getExternalHwcDisplayId() const = 0;
+    virtual std::optional<hal::HWDisplayId> getInternalHwcDisplayId() const = 0;
+    virtual std::optional<hal::HWDisplayId> getExternalHwcDisplayId() const = 0;
 
-    virtual std::optional<DisplayId> toPhysicalDisplayId(hwc2_display_t hwcDisplayId) const = 0;
-    virtual std::optional<hwc2_display_t> fromPhysicalDisplayId(DisplayId displayId) const = 0;
+    virtual std::optional<DisplayId> toPhysicalDisplayId(hal::HWDisplayId hwcDisplayId) const = 0;
+    virtual std::optional<hal::HWDisplayId> fromPhysicalDisplayId(DisplayId displayId) const = 0;
 };
 
 namespace impl {
@@ -230,19 +233,19 @@
 
     void setConfiguration(HWC2::ComposerCallback* callback, int32_t sequenceId) override;
 
-    bool getDisplayIdentificationData(hwc2_display_t hwcDisplayId, uint8_t* outPort,
+    bool getDisplayIdentificationData(hal::HWDisplayId hwcDisplayId, uint8_t* outPort,
                                       DisplayIdentificationData* outData) const override;
 
-    bool hasCapability(HWC2::Capability capability) const override;
+    bool hasCapability(hal::Capability capability) const override;
     bool hasDisplayCapability(DisplayId displayId,
-                              HWC2::DisplayCapability capability) const override;
+                              hal::DisplayCapability capability) const override;
 
     // Attempts to allocate a virtual display and returns its ID if created on the HWC device.
     std::optional<DisplayId> allocateVirtualDisplay(uint32_t width, uint32_t height,
                                                     ui::PixelFormat* format) override;
 
     // Called from SurfaceFlinger, when the state for a new physical display needs to be recreated.
-    void allocatePhysicalDisplay(hwc2_display_t hwcDisplayId, DisplayId displayId) override;
+    void allocatePhysicalDisplay(hal::HWDisplayId hwcDisplayId, DisplayId displayId) override;
 
     // Attempts to create a new layer on this display
     HWC2::Layer* createLayer(DisplayId displayId) override;
@@ -308,11 +311,11 @@
 
     // Returns stable display ID (and display name on connection of new or previously disconnected
     // display), or std::nullopt if hotplug event was ignored.
-    std::optional<DisplayIdentificationInfo> onHotplug(hwc2_display_t hwcDisplayId,
-                                                       HWC2::Connection connection) override;
+    std::optional<DisplayIdentificationInfo> onHotplug(hal::HWDisplayId hwcDisplayId,
+                                                       hal::Connection connection) override;
 
-    bool onVsync(hwc2_display_t hwcDisplayId, int64_t timestamp) override;
-    void setVsyncEnabled(DisplayId displayId, HWC2::Vsync enabled) override;
+    bool onVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp) override;
+    void setVsyncEnabled(DisplayId displayId, hal::Vsync enabled) override;
 
     nsecs_t getRefreshTimestamp(DisplayId displayId) const override;
     bool isConnected(DisplayId displayId) const override;
@@ -337,12 +340,11 @@
     bool isVsyncPeriodSwitchSupported(DisplayId displayId) const override;
     nsecs_t getDisplayVsyncPeriod(DisplayId displayId) const override;
     status_t setActiveConfigWithConstraints(DisplayId displayId, size_t configId,
-                                            const HWC2::VsyncPeriodChangeConstraints& constraints,
-                                            HWC2::VsyncPeriodChangeTimeline* outTimeline) override;
+                                            const hal::VsyncPeriodChangeConstraints& constraints,
+                                            hal::VsyncPeriodChangeTimeline* outTimeline) override;
     status_t setAutoLowLatencyMode(DisplayId displayId, bool) override;
-    status_t getSupportedContentTypes(DisplayId displayId,
-                                      std::vector<HWC2::ContentType>*) override;
-    status_t setContentType(DisplayId displayId, HWC2::ContentType) override;
+    status_t getSupportedContentTypes(DisplayId displayId, std::vector<hal::ContentType>*) override;
+    status_t setContentType(DisplayId displayId, hal::ContentType) override;
 
     const std::unordered_map<std::string, bool>& getSupportedLayerGenericMetadata() const override;
 
@@ -352,23 +354,23 @@
     Hwc2::Composer* getComposer() const override { return mComposer.get(); }
 
     // TODO(b/74619554): Remove special cases for internal/external display.
-    std::optional<hwc2_display_t> getInternalHwcDisplayId() const override {
+    std::optional<hal::HWDisplayId> getInternalHwcDisplayId() const override {
         return mInternalHwcDisplayId;
     }
-    std::optional<hwc2_display_t> getExternalHwcDisplayId() const override {
+    std::optional<hal::HWDisplayId> getExternalHwcDisplayId() const override {
         return mExternalHwcDisplayId;
     }
 
-    std::optional<DisplayId> toPhysicalDisplayId(hwc2_display_t hwcDisplayId) const override;
-    std::optional<hwc2_display_t> fromPhysicalDisplayId(DisplayId displayId) const override;
+    std::optional<DisplayId> toPhysicalDisplayId(hal::HWDisplayId hwcDisplayId) const override;
+    std::optional<hal::HWDisplayId> fromPhysicalDisplayId(DisplayId displayId) const override;
 
 private:
     // For unit tests
     friend TestableSurfaceFlinger;
 
-    std::optional<DisplayIdentificationInfo> onHotplugConnect(hwc2_display_t hwcDisplayId);
-    std::optional<DisplayIdentificationInfo> onHotplugDisconnect(hwc2_display_t hwcDisplayId);
-    bool shouldIgnoreHotplugConnect(hwc2_display_t hwcDisplayId,
+    std::optional<DisplayIdentificationInfo> onHotplugConnect(hal::HWDisplayId hwcDisplayId);
+    std::optional<DisplayIdentificationInfo> onHotplugDisconnect(hal::HWDisplayId hwcDisplayId);
+    bool shouldIgnoreHotplugConnect(hal::HWDisplayId hwcDisplayId,
                                     bool hasDisplayIdentificationData) const;
 
     void loadCapabilities();
@@ -386,12 +388,12 @@
                 std::shared_ptr<const HWC2::Display::Config>> configMap;
 
         bool validateWasSkipped;
-        HWC2::Error presentError;
+        hal::Error presentError;
 
         bool vsyncTraceToggle = false;
 
         std::mutex vsyncEnabledLock;
-        HWC2::Vsync vsyncEnabled GUARDED_BY(vsyncEnabledLock) = HWC2::Vsync::Disable;
+        hal::Vsync vsyncEnabled GUARDED_BY(vsyncEnabledLock) = hal::Vsync::DISABLE;
 
         mutable std::mutex lastHwVsyncLock;
         nsecs_t lastHwVsync GUARDED_BY(lastHwVsyncLock) = 0;
@@ -400,13 +402,13 @@
     std::unordered_map<DisplayId, DisplayData> mDisplayData;
 
     std::unique_ptr<android::Hwc2::Composer> mComposer;
-    std::unordered_set<HWC2::Capability> mCapabilities;
+    std::unordered_set<hal::Capability> mCapabilities;
     std::unordered_map<std::string, bool> mSupportedLayerGenericMetadata;
     bool mRegisteredCallback = false;
 
-    std::unordered_map<hwc2_display_t, DisplayId> mPhysicalDisplayIdMap;
-    std::optional<hwc2_display_t> mInternalHwcDisplayId;
-    std::optional<hwc2_display_t> mExternalHwcDisplayId;
+    std::unordered_map<hal::HWDisplayId, DisplayId> mPhysicalDisplayIdMap;
+    std::optional<hal::HWDisplayId> mInternalHwcDisplayId;
+    std::optional<hal::HWDisplayId> mExternalHwcDisplayId;
     bool mHasMultiDisplaySupport = false;
 
     std::unordered_set<DisplayId> mFreeVirtualDisplayIds;
diff --git a/services/surfaceflinger/DisplayHardware/Hal.h b/services/surfaceflinger/DisplayHardware/Hal.h
new file mode 100644
index 0000000..ac3917d
--- /dev/null
+++ b/services/surfaceflinger/DisplayHardware/Hal.h
@@ -0,0 +1,166 @@
+/*
+ * Copyright 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android/hardware/graphics/common/1.1/types.h>
+#include <android/hardware/graphics/composer/2.4/IComposer.h>
+#include <android/hardware/graphics/composer/2.4/IComposerClient.h>
+
+#define ERROR_HAS_CHANGES 5
+
+namespace android {
+namespace hardware::graphics::composer::hal {
+
+namespace types = android::hardware::graphics::common;
+namespace V2_1 = android::hardware::graphics::composer::V2_1;
+namespace V2_2 = android::hardware::graphics::composer::V2_2;
+namespace V2_3 = android::hardware::graphics::composer::V2_3;
+namespace V2_4 = android::hardware::graphics::composer::V2_4;
+
+using types::V1_0::ColorTransform;
+using types::V1_0::Transform;
+using types::V1_1::RenderIntent;
+using types::V1_2::ColorMode;
+using types::V1_2::Dataspace;
+using types::V1_2::Hdr;
+using types::V1_2::PixelFormat;
+
+using V2_1::Error;
+using V2_4::IComposer;
+using V2_4::IComposerCallback;
+using V2_4::IComposerClient;
+using V2_4::VsyncPeriodChangeTimeline;
+using V2_4::VsyncPeriodNanos;
+
+using Attribute = IComposerClient::Attribute;
+using BlendMode = IComposerClient::BlendMode;
+using Color = IComposerClient::Color;
+using Composition = IComposerClient::Composition;
+using Connection = IComposerCallback::Connection;
+using ContentType = IComposerClient::ContentType;
+using Capability = IComposer::Capability;
+using DisplayCapability = IComposerClient::DisplayCapability;
+using DisplayRequest = IComposerClient::DisplayRequest;
+using DisplayType = IComposerClient::DisplayType;
+using HWConfigId = V2_1::Config;
+using HWDisplayId = V2_1::Display;
+using HWError = V2_1::Error;
+using HWLayerId = V2_1::Layer;
+using LayerGenericMetadataKey = IComposerClient::LayerGenericMetadataKey;
+using LayerRequest = IComposerClient::LayerRequest;
+using PerFrameMetadata = IComposerClient::PerFrameMetadata;
+using PerFrameMetadataKey = IComposerClient::PerFrameMetadataKey;
+using PerFrameMetadataBlob = IComposerClient::PerFrameMetadataBlob;
+using PowerMode = IComposerClient::PowerMode;
+using Vsync = IComposerClient::Vsync;
+using VsyncPeriodChangeConstraints = IComposerClient::VsyncPeriodChangeConstraints;
+
+} // namespace hardware::graphics::composer::hal
+
+inline bool hasChangesError(hardware::graphics::composer::hal::Error error) {
+    return ERROR_HAS_CHANGES == static_cast<int32_t>(error);
+}
+
+inline std::string to_string(hardware::graphics::composer::hal::Attribute attribute) {
+    switch (attribute) {
+        case hardware::graphics::composer::hal::Attribute::INVALID:
+            return "Invalid";
+        case hardware::graphics::composer::hal::Attribute::WIDTH:
+            return "Width";
+        case hardware::graphics::composer::hal::Attribute::HEIGHT:
+            return "Height";
+        case hardware::graphics::composer::hal::Attribute::VSYNC_PERIOD:
+            return "VsyncPeriod";
+        case hardware::graphics::composer::hal::Attribute::DPI_X:
+            return "DpiX";
+        case hardware::graphics::composer::hal::Attribute::DPI_Y:
+            return "DpiY";
+        default:
+            return "Unknown";
+    }
+}
+
+inline std::string to_string(hardware::graphics::composer::hal::Composition composition) {
+    switch (composition) {
+        case hardware::graphics::composer::hal::Composition::INVALID:
+            return "Invalid";
+        case hardware::graphics::composer::hal::Composition::CLIENT:
+            return "Client";
+        case hardware::graphics::composer::hal::Composition::DEVICE:
+            return "Device";
+        case hardware::graphics::composer::hal::Composition::SOLID_COLOR:
+            return "SolidColor";
+        case hardware::graphics::composer::hal::Composition::CURSOR:
+            return "Cursor";
+        case hardware::graphics::composer::hal::Composition::SIDEBAND:
+            return "Sideband";
+        default:
+            return "Unknown";
+    }
+}
+
+inline std::string to_string(hardware::graphics::composer::hal::V2_4::Error error) {
+    // 5 is reserved for historical reason, during validation 5 means has changes.
+    if (ERROR_HAS_CHANGES == static_cast<int32_t>(error)) {
+        return "HasChanges";
+    }
+    switch (error) {
+        case hardware::graphics::composer::hal::V2_4::Error::NONE:
+            return "None";
+        case hardware::graphics::composer::hal::V2_4::Error::BAD_CONFIG:
+            return "BadConfig";
+        case hardware::graphics::composer::hal::V2_4::Error::BAD_DISPLAY:
+            return "BadDisplay";
+        case hardware::graphics::composer::hal::V2_4::Error::BAD_LAYER:
+            return "BadLayer";
+        case hardware::graphics::composer::hal::V2_4::Error::BAD_PARAMETER:
+            return "BadParameter";
+        case hardware::graphics::composer::hal::V2_4::Error::NO_RESOURCES:
+            return "NoResources";
+        case hardware::graphics::composer::hal::V2_4::Error::NOT_VALIDATED:
+            return "NotValidated";
+        case hardware::graphics::composer::hal::V2_4::Error::UNSUPPORTED:
+            return "Unsupported";
+        case hardware::graphics::composer::hal::V2_4::Error::SEAMLESS_NOT_ALLOWED:
+            return "SeamlessNotAllowed";
+        case hardware::graphics::composer::hal::V2_4::Error::SEAMLESS_NOT_POSSIBLE:
+            return "SeamlessNotPossible";
+        default:
+            return "Unknown";
+    }
+}
+
+inline std::string to_string(hardware::graphics::composer::hal::Error error) {
+    return to_string(static_cast<hardware::graphics::composer::hal::V2_4::Error>(error));
+}
+
+inline std::string to_string(hardware::graphics::composer::hal::PowerMode mode) {
+    switch (mode) {
+        case hardware::graphics::composer::hal::PowerMode::OFF:
+            return "Off";
+        case hardware::graphics::composer::hal::PowerMode::DOZE_SUSPEND:
+            return "DozeSuspend";
+        case hardware::graphics::composer::hal::PowerMode::DOZE:
+            return "Doze";
+        case hardware::graphics::composer::hal::PowerMode::ON:
+            return "On";
+        default:
+            return "Unknown";
+    }
+}
+
+} // namespace android
diff --git a/services/surfaceflinger/DisplayHardware/PowerAdvisor.h b/services/surfaceflinger/DisplayHardware/PowerAdvisor.h
index 4a90acb..34e63e7 100644
--- a/services/surfaceflinger/DisplayHardware/PowerAdvisor.h
+++ b/services/surfaceflinger/DisplayHardware/PowerAdvisor.h
@@ -16,12 +16,6 @@
 
 #pragma once
 
-#define HWC2_INCLUDE_STRINGIFICATION
-#define HWC2_USE_CPP11
-#include <hardware/hwcomposer2.h>
-#undef HWC2_INCLUDE_STRINGIFICATION
-#undef HWC2_USE_CPP11
-
 #include <atomic>
 #include <unordered_set>
 
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index 5039761..8452957 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -220,9 +220,6 @@
     }
 
     mFlinger->markLayerPendingRemovalLocked(this);
-    if (hasInput()) {
-        mFlinger->dirtyInput();
-    }
 }
 
 void Layer::onRemovedFromCurrentState() {
@@ -998,8 +995,6 @@
     mPendingStatesSnapshot = mPendingStates;
     mCurrentState.callbackHandles = {};
 
-    maybeDirtyInput();
-
     return flags;
 }
 
@@ -1384,6 +1379,9 @@
         return false;
     }
 
+    // Activate the layer in Scheduler's LayerHistory
+    mFlinger->mScheduler->recordLayerHistory(this, systemTime());
+
     mCurrentState.sequence++;
     mCurrentState.frameRate = frameRate;
     mCurrentState.modified = true;
@@ -2545,32 +2543,6 @@
     }
 }
 
-bool Layer::maybeDirtyInput() {
-    // No sense redirtying input.
-    if (mFlinger->inputDirty()) return true;
-
-    if (hasInput()) {
-        mFlinger->dirtyInput();
-        return true;
-    }
-
-    // If a child or relative dirties the input, no sense continuing to traverse
-    // so we return early and halt the recursion. We traverse ourselves instead
-    // of using traverse() so we can implement this early halt.
-    for (const sp<Layer>& child : mDrawingChildren) {
-        if (child->maybeDirtyInput()) {
-            return true;
-        }
-    }
-    for (const wp<Layer>& weakRelative : mDrawingState.zOrderRelatives) {
-        sp<Layer> relative = weakRelative.promote();
-        if (relative && relative->maybeDirtyInput()) {
-            return true;
-        }
-    }
-    return false;
-}
-
 // ---------------------------------------------------------------------------
 
 }; // namespace android
diff --git a/services/surfaceflinger/Layer.h b/services/surfaceflinger/Layer.h
index 92ac015..6636b5e 100644
--- a/services/surfaceflinger/Layer.h
+++ b/services/surfaceflinger/Layer.h
@@ -1015,10 +1015,6 @@
     // Window types from WindowManager.LayoutParams
     const int mWindowType;
 
-    // Called when mDrawingState has changed. If we or one of our children/relatives hasInput()
-    // then we will dirty the setInputWindows cache.
-    bool maybeDirtyInput();
-
 private:
     /**
      * Returns an unsorted vector of all layers that are part of this tree.
diff --git a/services/surfaceflinger/Scheduler/DispSync.cpp b/services/surfaceflinger/Scheduler/DispSync.cpp
index 809a0e5..fc6ccae 100644
--- a/services/surfaceflinger/Scheduler/DispSync.cpp
+++ b/services/surfaceflinger/Scheduler/DispSync.cpp
@@ -768,9 +768,8 @@
     }
 }
 
-nsecs_t DispSync::computeNextRefresh(int periodOffset) const {
+nsecs_t DispSync::computeNextRefresh(int periodOffset, nsecs_t now) const {
     Mutex::Autolock lock(mMutex);
-    nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
     nsecs_t phase = mReferenceTime + mPhase;
     if (mPeriod == 0) {
         return 0;
@@ -837,7 +836,7 @@
     StringAppendF(&result, "current monotonic time: %" PRId64 "\n", now);
 }
 
-nsecs_t DispSync::expectedPresentTime() {
+nsecs_t DispSync::expectedPresentTime(nsecs_t now) {
     // The HWC doesn't currently have a way to report additional latency.
     // Assume that whatever we submit now will appear right after the flip.
     // For a smart panel this might be 1.  This is expressed in frames,
@@ -846,7 +845,7 @@
     const uint32_t hwcLatency = 0;
 
     // Ask DispSync when the next refresh will be (CLOCK_MONOTONIC).
-    return computeNextRefresh(hwcLatency);
+    return computeNextRefresh(hwcLatency, now);
 }
 
 } // namespace impl
diff --git a/services/surfaceflinger/Scheduler/DispSync.h b/services/surfaceflinger/Scheduler/DispSync.h
index 2d9afc9..2faa81c 100644
--- a/services/surfaceflinger/Scheduler/DispSync.h
+++ b/services/surfaceflinger/Scheduler/DispSync.h
@@ -58,9 +58,9 @@
                                       nsecs_t lastCallbackTime) = 0;
     virtual status_t removeEventListener(Callback* callback, nsecs_t* outLastCallback) = 0;
     virtual status_t changePhaseOffset(Callback* callback, nsecs_t phase) = 0;
-    virtual nsecs_t computeNextRefresh(int periodOffset) const = 0;
+    virtual nsecs_t computeNextRefresh(int periodOffset, nsecs_t now) const = 0;
     virtual void setIgnorePresentFences(bool ignore) = 0;
-    virtual nsecs_t expectedPresentTime() = 0;
+    virtual nsecs_t expectedPresentTime(nsecs_t now) = 0;
 
     virtual void dump(std::string& result) const = 0;
 
@@ -167,7 +167,7 @@
     // The periodOffset value can be used to move forward or backward; an
     // offset of zero is the next refresh, -1 is the previous refresh, 1 is
     // the refresh after next. etc.
-    nsecs_t computeNextRefresh(int periodOffset) const override;
+    nsecs_t computeNextRefresh(int periodOffset, nsecs_t now) const override;
 
     // In certain situations the present fences aren't a good indicator of vsync
     // time, e.g. when vr flinger is active, or simply aren't available,
@@ -178,7 +178,7 @@
     void setIgnorePresentFences(bool ignore) override;
 
     // Determine the expected present time when a buffer acquired now will be displayed.
-    nsecs_t expectedPresentTime();
+    nsecs_t expectedPresentTime(nsecs_t now);
 
     // dump appends human-readable debug info to the result string.
     void dump(std::string& result) const override;
diff --git a/services/surfaceflinger/Scheduler/LayerHistoryV2.cpp b/services/surfaceflinger/Scheduler/LayerHistoryV2.cpp
index 8b08592..b067466 100644
--- a/services/surfaceflinger/Scheduler/LayerHistoryV2.cpp
+++ b/services/surfaceflinger/Scheduler/LayerHistoryV2.cpp
@@ -40,9 +40,11 @@
 namespace {
 
 bool isLayerActive(const Layer& layer, const LayerInfoV2& info, nsecs_t threshold) {
+    // Layers with an explicit vote are always kept active
     if (layer.getFrameRateForLayerTree().rate > 0) {
-        return layer.isVisible();
+        return true;
     }
+
     return layer.isVisible() && info.getLastUpdatedTime() >= threshold;
 }
 
@@ -127,29 +129,24 @@
         //  an additional parameter.
         ALOGV("Layer has priority: %d", strong->getFrameRateSelectionPriority());
 
-        const bool recent = info->isRecentlyActive(now);
-        if (recent) {
-            const auto [type, refreshRate] = info->getRefreshRate(now);
-            // Skip NoVote layer as those don't have any requirements
-            if (type == LayerHistory::LayerVoteType::NoVote) {
-                continue;
-            }
+        const auto [type, refreshRate] = info->getRefreshRate(now);
+        // Skip NoVote layer as those don't have any requirements
+        if (type == LayerHistory::LayerVoteType::NoVote) {
+            continue;
+        }
 
-            // Compute the layer's position on the screen
-            const Rect bounds = Rect(strong->getBounds());
-            const ui::Transform transform = strong->getTransform();
-            constexpr bool roundOutwards = true;
-            Rect transformed = transform.transform(bounds, roundOutwards);
+        // Compute the layer's position on the screen
+        const Rect bounds = Rect(strong->getBounds());
+        const ui::Transform transform = strong->getTransform();
+        constexpr bool roundOutwards = true;
+        Rect transformed = transform.transform(bounds, roundOutwards);
 
-            const float layerArea = transformed.getWidth() * transformed.getHeight();
-            float weight = mDisplayArea ? layerArea / mDisplayArea : 0.0f;
-            summary.push_back({strong->getName(), type, refreshRate, weight});
+        const float layerArea = transformed.getWidth() * transformed.getHeight();
+        float weight = mDisplayArea ? layerArea / mDisplayArea : 0.0f;
+        summary.push_back({strong->getName(), type, refreshRate, weight});
 
-            if (CC_UNLIKELY(mTraceEnabled)) {
-                trace(layer, type, static_cast<int>(std::round(refreshRate)));
-            }
-        } else if (CC_UNLIKELY(mTraceEnabled)) {
-            trace(layer, LayerHistory::LayerVoteType::NoVote, 0);
+        if (CC_UNLIKELY(mTraceEnabled)) {
+            trace(layer, type, static_cast<int>(std::round(refreshRate)));
         }
     }
 
@@ -177,7 +174,7 @@
                         return LayerVoteType::NoVote;
                 }
             }();
-            if (frameRate.rate > 0 || voteType == LayerVoteType::NoVote) {
+            if (layer->isVisible() && (frameRate.rate > 0 || voteType == LayerVoteType::NoVote)) {
                 info->setLayerVote(voteType, frameRate.rate);
             } else {
                 info->resetLayerVote();
diff --git a/services/surfaceflinger/Scheduler/LayerInfoV2.cpp b/services/surfaceflinger/Scheduler/LayerInfoV2.cpp
index b4365bf..bf1fb88 100644
--- a/services/surfaceflinger/Scheduler/LayerInfoV2.cpp
+++ b/services/surfaceflinger/Scheduler/LayerInfoV2.cpp
@@ -45,15 +45,6 @@
     }
 }
 
-// Returns whether the earliest present time is within the active threshold.
-bool LayerInfoV2::isRecentlyActive(nsecs_t now) const {
-    if (mFrameTimes.empty()) {
-        return false;
-    }
-
-    return mFrameTimes.back().queueTime >= getActiveLayerThreshold(now);
-}
-
 bool LayerInfoV2::isFrameTimeValid(const FrameTimeData& frameTime) const {
     return frameTime.queueTime >= std::chrono::duration_cast<std::chrono::nanoseconds>(
                                           mFrameTimeValidSince.time_since_epoch())
diff --git a/services/surfaceflinger/Scheduler/LayerInfoV2.h b/services/surfaceflinger/Scheduler/LayerInfoV2.h
index 25fb95a..ad91f18 100644
--- a/services/surfaceflinger/Scheduler/LayerInfoV2.h
+++ b/services/surfaceflinger/Scheduler/LayerInfoV2.h
@@ -64,8 +64,6 @@
     // updated time, the updated time is the present time.
     void setLastPresentTime(nsecs_t lastPresentTime, nsecs_t now);
 
-    bool isRecentlyActive(nsecs_t now) const;
-
     // Sets an explicit layer vote. This usually comes directly from the application via
     // ANativeWindow_setFrameRate API
     void setLayerVote(LayerHistory::LayerVoteType type, float fps) { mLayerVote = {type, fps}; }
diff --git a/services/surfaceflinger/Scheduler/MessageQueue.cpp b/services/surfaceflinger/Scheduler/MessageQueue.cpp
index 005d157..d8a666a 100644
--- a/services/surfaceflinger/Scheduler/MessageQueue.cpp
+++ b/services/surfaceflinger/Scheduler/MessageQueue.cpp
@@ -62,8 +62,9 @@
     }
 }
 
-void MessageQueue::Handler::dispatchInvalidate() {
+void MessageQueue::Handler::dispatchInvalidate(nsecs_t timestamp) {
     if ((android_atomic_or(eventMaskInvalidate, &mEventMask) & eventMaskInvalidate) == 0) {
+        mLastVsyncTime = timestamp;
         mQueue.mLooper->sendMessage(this, Message(MessageQueue::INVALIDATE));
     }
 }
@@ -72,11 +73,11 @@
     switch (message.what) {
         case INVALIDATE:
             android_atomic_and(~eventMaskInvalidate, &mEventMask);
-            mQueue.mFlinger->onMessageReceived(message.what);
+            mQueue.mFlinger->onMessageReceived(message.what, mLastVsyncTime);
             break;
         case REFRESH:
             android_atomic_and(~eventMaskRefresh, &mEventMask);
-            mQueue.mFlinger->onMessageReceived(message.what);
+            mQueue.mFlinger->onMessageReceived(message.what, mLastVsyncTime);
             break;
     }
 }
@@ -151,7 +152,7 @@
     while ((n = DisplayEventReceiver::getEvents(&mEventTube, buffer, 8)) > 0) {
         for (int i = 0; i < n; i++) {
             if (buffer[i].header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC) {
-                mHandler->dispatchInvalidate();
+                mHandler->dispatchInvalidate(buffer[i].header.timestamp);
                 break;
             }
         }
diff --git a/services/surfaceflinger/Scheduler/MessageQueue.h b/services/surfaceflinger/Scheduler/MessageQueue.h
index fcfc4aa..dbd5e96 100644
--- a/services/surfaceflinger/Scheduler/MessageQueue.h
+++ b/services/surfaceflinger/Scheduler/MessageQueue.h
@@ -101,12 +101,13 @@
         enum { eventMaskInvalidate = 0x1, eventMaskRefresh = 0x2, eventMaskTransaction = 0x4 };
         MessageQueue& mQueue;
         int32_t mEventMask;
+        std::atomic<nsecs_t> mLastVsyncTime;
 
     public:
         explicit Handler(MessageQueue& queue) : mQueue(queue), mEventMask(0) {}
         virtual void handleMessage(const Message& message);
         void dispatchRefresh();
-        void dispatchInvalidate();
+        void dispatchInvalidate(nsecs_t timestamp);
     };
 
     friend class Handler;
diff --git a/services/surfaceflinger/Scheduler/Scheduler.cpp b/services/surfaceflinger/Scheduler/Scheduler.cpp
index 9a9523f..3a84b67 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.cpp
+++ b/services/surfaceflinger/Scheduler/Scheduler.cpp
@@ -250,7 +250,7 @@
 }
 
 void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats) {
-    stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
+    stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0, systemTime());
     stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
 }
 
@@ -378,8 +378,8 @@
     mPrimaryDispSync->setIgnorePresentFences(ignore);
 }
 
-nsecs_t Scheduler::getDispSyncExpectedPresentTime() {
-    return mPrimaryDispSync->expectedPresentTime();
+nsecs_t Scheduler::getDispSyncExpectedPresentTime(nsecs_t now) {
+    return mPrimaryDispSync->expectedPresentTime(now);
 }
 
 void Scheduler::registerLayer(Layer* layer) {
@@ -634,7 +634,7 @@
     return mFeatures.configId;
 }
 
-void Scheduler::onNewVsyncPeriodChangeTimeline(const HWC2::VsyncPeriodChangeTimeline& timeline) {
+void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
     if (timeline.refreshRequired) {
         mSchedulerCallback.repaintEverythingForHWC();
     }
diff --git a/services/surfaceflinger/Scheduler/Scheduler.h b/services/surfaceflinger/Scheduler/Scheduler.h
index 04cc96a..75c02f3 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.h
+++ b/services/surfaceflinger/Scheduler/Scheduler.h
@@ -114,7 +114,7 @@
                          bool* periodFlushed);
     void addPresentFence(const std::shared_ptr<FenceTime>&);
     void setIgnorePresentFences(bool ignore);
-    nsecs_t getDispSyncExpectedPresentTime();
+    nsecs_t getDispSyncExpectedPresentTime(nsecs_t now);
 
     // Layers are registered on creation, and unregistered when the weak reference expires.
     void registerLayer(Layer*);
@@ -138,7 +138,7 @@
     std::optional<HwcConfigIndexType> getPreferredConfigId();
 
     // Notifies the scheduler about a refresh rate timeline change.
-    void onNewVsyncPeriodChangeTimeline(const HWC2::VsyncPeriodChangeTimeline& timeline);
+    void onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline);
 
     // Notifies the scheduler when the display was refreshed
     void onDisplayRefreshed(nsecs_t timestamp);
@@ -242,7 +242,7 @@
     const scheduler::RefreshRateConfigs& mRefreshRateConfigs;
 
     std::mutex mVsyncTimelineLock;
-    std::optional<HWC2::VsyncPeriodChangeTimeline> mLastVsyncPeriodChangeTimeline
+    std::optional<hal::VsyncPeriodChangeTimeline> mLastVsyncPeriodChangeTimeline
             GUARDED_BY(mVsyncTimelineLock);
     static constexpr std::chrono::nanoseconds MAX_VSYNC_APPLIED_TIME = 200ms;
 
diff --git a/services/surfaceflinger/Scheduler/VSyncReactor.cpp b/services/surfaceflinger/Scheduler/VSyncReactor.cpp
index 892ae62..2f1faac 100644
--- a/services/surfaceflinger/Scheduler/VSyncReactor.cpp
+++ b/services/surfaceflinger/Scheduler/VSyncReactor.cpp
@@ -221,14 +221,13 @@
     }
 }
 
-nsecs_t VSyncReactor::computeNextRefresh(int periodOffset) const {
-    auto const now = mClock->now();
+nsecs_t VSyncReactor::computeNextRefresh(int periodOffset, nsecs_t now) const {
     auto const currentPeriod = periodOffset ? mTracker->currentPeriod() : 0;
     return mTracker->nextAnticipatedVSyncTimeFrom(now + periodOffset * currentPeriod);
 }
 
-nsecs_t VSyncReactor::expectedPresentTime() {
-    return mTracker->nextAnticipatedVSyncTimeFrom(mClock->now());
+nsecs_t VSyncReactor::expectedPresentTime(nsecs_t now) {
+    return mTracker->nextAnticipatedVSyncTimeFrom(now);
 }
 
 void VSyncReactor::startPeriodTransition(nsecs_t newPeriod) {
diff --git a/services/surfaceflinger/Scheduler/VSyncReactor.h b/services/surfaceflinger/Scheduler/VSyncReactor.h
index 5ee29f8..31ddf5a 100644
--- a/services/surfaceflinger/Scheduler/VSyncReactor.h
+++ b/services/surfaceflinger/Scheduler/VSyncReactor.h
@@ -42,8 +42,8 @@
     bool addPresentFence(const std::shared_ptr<FenceTime>& fence) final;
     void setIgnorePresentFences(bool ignoration) final;
 
-    nsecs_t computeNextRefresh(int periodOffset) const final;
-    nsecs_t expectedPresentTime() final;
+    nsecs_t computeNextRefresh(int periodOffset, nsecs_t now) const final;
+    nsecs_t expectedPresentTime(nsecs_t now) final;
 
     void setPeriod(nsecs_t period) final;
     nsecs_t getPeriod() final;
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index ddf0775..57b1f32 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -140,6 +140,8 @@
 using ui::Hdr;
 using ui::RenderIntent;
 
+namespace hal = android::hardware::graphics::composer::hal;
+
 namespace {
 
 #pragma clang diagnostic push
@@ -169,19 +171,22 @@
 
 #pragma clang diagnostic pop
 
-class ConditionalLock {
-public:
-    ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
-        if (lock) {
-            mMutex.lock();
-        }
+template <typename Mutex>
+struct ConditionalLockGuard {
+    ConditionalLockGuard(Mutex& mutex, bool lock) : mutex(mutex), lock(lock) {
+        if (lock) mutex.lock();
     }
-    ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
-private:
-    Mutex& mMutex;
-    bool mLocked;
+
+    ~ConditionalLockGuard() {
+        if (lock) mutex.unlock();
+    }
+
+    Mutex& mutex;
+    const bool lock;
 };
 
+using ConditionalLock = ConditionalLockGuard<Mutex>;
+
 // TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
 constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
 
@@ -689,7 +694,7 @@
     // Inform native graphics APIs whether the present timestamp is supported:
 
     const bool presentFenceReliable =
-            !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
+            !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
     mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
 
     if (mStartPropertySetThread->Start() != NO_ERROR) {
@@ -767,8 +772,7 @@
     };
     ConditionalLock _l(mStateLock,
             std::this_thread::get_id() != mMainThreadId);
-    if (!getHwComposer().hasCapability(
-            HWC2::Capability::PresentFenceIsNotReliable)) {
+    if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
         outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
     }
     return NO_ERROR;
@@ -1096,11 +1100,11 @@
     ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
 
     // TODO(b/142753666) use constrains
-    HWC2::VsyncPeriodChangeConstraints constraints;
+    hal::VsyncPeriodChangeConstraints constraints;
     constraints.desiredTimeNanos = systemTime();
     constraints.seamlessRequired = false;
 
-    HWC2::VsyncPeriodChangeTimeline outTimeline;
+    hal::VsyncPeriodChangeTimeline outTimeline;
     auto status =
             getHwComposer().setActiveConfigWithConstraints(*displayId,
                                                            mUpcomingActiveConfig.configId.value(),
@@ -1216,8 +1220,9 @@
     if (!displayId) {
         return NAME_NOT_FOUND;
     }
-    *outSupport = getHwComposer().hasDisplayCapability(*displayId,
-                                                       HWC2::DisplayCapability::AutoLowLatencyMode);
+    *outSupport =
+            getHwComposer().hasDisplayCapability(*displayId,
+                                                 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
     return NO_ERROR;
 }
 
@@ -1244,18 +1249,18 @@
         return NAME_NOT_FOUND;
     }
 
-    std::vector<HWC2::ContentType> types;
+    std::vector<hal::ContentType> types;
     getHwComposer().getSupportedContentTypes(*displayId, &types);
 
     *outSupport = std::any_of(types.begin(), types.end(),
-                              [](auto type) { return type == HWC2::ContentType::Game; });
+                              [](auto type) { return type == hal::ContentType::GAME; });
     return NO_ERROR;
 }
 
 void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
     postMessageAsync(new LambdaMessage([=] {
         if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
-            const auto type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
+            const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
             getHwComposer().setContentType(*displayId, type);
         } else {
             ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
@@ -1474,7 +1479,7 @@
         return NAME_NOT_FOUND;
     }
     *outSupport =
-            getHwComposer().hasDisplayCapability(*displayId, HWC2::DisplayCapability::Brightness);
+            getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
     return NO_ERROR;
 }
 
@@ -1568,9 +1573,9 @@
     return getHwComposer().getDisplayVsyncPeriod(*displayId);
 }
 
-void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
+void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
                                      int64_t timestamp,
-                                     std::optional<hwc2_vsync_period_t> vsyncPeriod) {
+                                     std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
     ATRACE_NAME("SF onVsync");
 
     Mutex::Autolock lock(mStateLock);
@@ -1622,10 +1627,10 @@
     setDesiredActiveConfig({refreshRate.getConfigId(), event});
 }
 
-void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
-                                       HWC2::Connection connection) {
+void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
+                                       hal::Connection connection) {
     ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
-          connection == HWC2::Connection::Connected ? "connected" : "disconnected");
+          connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
 
     // Ignore events that do not have the right sequenceId.
     if (sequenceId != getBE().mComposerSequenceId) {
@@ -1649,8 +1654,8 @@
 }
 
 void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
-        int32_t sequenceId, hwc2_display_t /*display*/,
-        const hwc_vsync_period_change_timeline_t& updatedTimeline) {
+        int32_t sequenceId, hal::HWDisplayId /*display*/,
+        const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
     Mutex::Autolock lock(mStateLock);
     if (sequenceId != getBE().mComposerSequenceId) {
         return;
@@ -1658,12 +1663,12 @@
     mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
 }
 
-void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
+void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
     // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
     // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
 }
 
-void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
+void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
     Mutex::Autolock lock(mStateLock);
     if (sequenceId != getBE().mComposerSequenceId) {
         return;
@@ -1683,7 +1688,7 @@
 void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
     ATRACE_CALL();
 
-    mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
+    mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
 
     if (const auto displayId = getInternalDisplayIdLocked()) {
         sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
@@ -1819,16 +1824,16 @@
     return fence->getSignalTime();
 }
 
-void SurfaceFlinger::populateExpectedPresentTime() {
+void SurfaceFlinger::populateExpectedPresentTime(nsecs_t wakeupTime) {
     DisplayStatInfo stats;
     mScheduler->getDisplayStatInfo(&stats);
-    const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
+    const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(wakeupTime);
     // Inflate the expected present time if we're targetting the next vsync.
     mExpectedPresentTime.store(
             mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
 }
 
-void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
+void SurfaceFlinger::onMessageReceived(int32_t what, nsecs_t when) NO_THREAD_SAFETY_ANALYSIS {
     ATRACE_CALL();
     switch (what) {
         case MessageQueue::INVALIDATE: {
@@ -1837,7 +1842,7 @@
             // value throughout this frame to make sure all layers are
             // seeing this same value.
             const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
-            populateExpectedPresentTime();
+            populateExpectedPresentTime(when);
 
             // When Backpressure propagation is enabled we want to give a small grace period
             // for the present fence to fire instead of just giving up on this frame to handle cases
@@ -1953,8 +1958,15 @@
             // potentially trigger a display handoff.
             updateVrFlinger();
 
+            if (mTracingEnabledChanged) {
+                mTracingEnabled = mTracing.isEnabled();
+                mTracingEnabledChanged = false;
+            }
+
             bool refreshNeeded;
-            withTracingLock([&]() {
+            {
+                ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
+
                 refreshNeeded = handleMessageTransaction();
                 refreshNeeded |= handleMessageInvalidate();
                 if (mTracingEnabled) {
@@ -1964,7 +1976,7 @@
                         mTracing.notifyLocked("visibleRegionsDirty");
                     }
                 }
-            });
+            }
 
             // Layers need to get updated (in the previous line) before we can use them for
             // choosing the refresh rate.
@@ -2084,6 +2096,8 @@
     postFrame();
     postComposition();
 
+    const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
+
     mHadClientComposition =
             std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
                 auto& displayDevice = tokenDisplayPair.second;
@@ -2101,6 +2115,11 @@
                 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
             });
 
+    // Only report a strategy change if we move in and out of composition with hw overlays
+    if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
+        mTimeStats->incrementCompositionStrategyChanges();
+    }
+
     mVSyncModulator->onRefreshed(mHadClientComposition);
 
     mLayersWithQueuedFrames.clear();
@@ -2408,7 +2427,7 @@
         const DisplayId displayId = info->id;
         const auto it = mPhysicalDisplayTokens.find(displayId);
 
-        if (event.connection == HWC2::Connection::Connected) {
+        if (event.connection == hal::Connection::CONNECTED) {
             if (it == mPhysicalDisplayTokens.end()) {
                 ALOGV("Creating display %s", to_string(displayId).c_str());
 
@@ -2878,19 +2897,6 @@
 void SurfaceFlinger::updateInputWindowInfo() {
     std::vector<InputWindowInfo> inputHandles;
 
-    // We use a simple caching algorithm here. mInputDirty begins as true,
-    // after we call setInputWindows we set it to false, so
-    // in the future we wont call it again.. We set input dirty to true again
-    // when any layer that hasInput() has a transaction performed on it
-    // or when any parent or relative parent of such a layer has a transaction
-    // performed on it. Not all of these transactions will really result in
-    // input changes but all input changes will spring from these transactions
-    // so the cache is safe but not optimal. It seems like it might be annoyingly
-    // costly to cache and comapre the actual InputWindowHandle vector though.
-    if (!mInputDirty && !mInputWindowCommands.syncInputWindows) {
-        return;
-    }
-
     mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
         if (layer->hasInput()) {
             // When calculating the screen bounds we ignore the transparent region since it may
@@ -2902,8 +2908,6 @@
     mInputFlinger->setInputWindows(inputHandles,
                                    mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
                                                                          : nullptr);
-
-    mInputDirty = false;
 }
 
 void SurfaceFlinger::commitInputWindowCommands() {
@@ -3037,26 +3041,6 @@
     mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
 }
 
-void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
-    if (mTracingEnabledChanged) {
-        mTracingEnabled = mTracing.isEnabled();
-        mTracingEnabledChanged = false;
-    }
-
-    // Synchronize with Tracing thread
-    std::unique_lock<std::mutex> lock;
-    if (mTracingEnabled) {
-        lock = std::unique_lock<std::mutex>(mDrawingStateLock);
-    }
-
-    lockedOperation();
-
-    // Synchronize with Tracing thread
-    if (mTracingEnabled) {
-        lock.unlock();
-    }
-}
-
 void SurfaceFlinger::commitOffscreenLayers() {
     for (Layer* offscreenLayer : mOffscreenLayers) {
         offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
@@ -3289,8 +3273,7 @@
 bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
                                                    bool useCachedExpectedPresentTime,
                                                    const Vector<ComposerState>& states) {
-    if (!useCachedExpectedPresentTime)
-        populateExpectedPresentTime();
+    if (!useCachedExpectedPresentTime) populateExpectedPresentTime(systemTime());
 
     const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
     // Do not present if the desiredPresentTime has not passed unless it is more than one second
@@ -4144,7 +4127,7 @@
             new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
 }
 
-void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
+void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, hal::Vsync enabled) {
     if (mHWCVsyncState != enabled) {
         getHwComposer().setVsyncEnabled(displayId, enabled);
         mHWCVsyncState = enabled;
@@ -4198,7 +4181,7 @@
         }
 
         // Make sure HWVsync is disabled before turning off the display
-        setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
+        setVsyncEnabledInHWC(*displayId, hal::Vsync::DISABLE);
 
         getHwComposer().setPowerMode(*displayId, mode);
         mVisibleRegionsDirty = true;
@@ -4401,11 +4384,19 @@
 
     scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
     StringAppendF(&result,
-                  "DesiredDisplayConfigSpecs: default config ID: %d"
+                  "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
                   ", min: %.2f Hz, max: %.2f Hz",
                   policy.defaultConfig.value(), policy.minRefreshRate, policy.maxRefreshRate);
     StringAppendF(&result, "(config override by backdoor: %s)\n\n",
                   mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
+    scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
+    if (currentPolicy != policy) {
+        StringAppendF(&result,
+                      "DesiredDisplayConfigSpecs (Override): default config ID: %d"
+                      ", min: %.2f Hz, max: %.2f Hz\n\n",
+                      currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
+                      currentPolicy.maxRefreshRate);
+    }
 
     mScheduler->dump(mAppConnectionHandle, result);
     mScheduler->getPrimaryDispSync().dump(result);
@@ -4526,7 +4517,7 @@
 
 void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
                                                       std::string& result) const {
-    hwc2_display_t hwcDisplayId;
+    hal::HWDisplayId hwcDisplayId;
     uint8_t port;
     DisplayIdentificationData data;
 
@@ -4563,11 +4554,13 @@
     result.append("\n");
 }
 
-LayersProto SurfaceFlinger::dumpDrawingStateProto(
-        uint32_t traceFlags, const sp<const DisplayDevice>& displayDevice) const {
+LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
+    // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
+    const auto display = getDefaultDisplayDeviceLocked();
+
     LayersProto layersProto;
     for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
-        layer->writeToProto(layersProto, traceFlags, displayDevice);
+        layer->writeToProto(layersProto, traceFlags, display);
     }
 
     return layersProto;
@@ -4599,10 +4592,7 @@
 
 LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
     LayersProto layersProto;
-    postMessageSync(new LambdaMessage([&]() {
-        const auto& displayDevice = getDefaultDisplayDeviceLocked();
-        layersProto = dumpDrawingStateProto(traceFlags, displayDevice);
-    }));
+    postMessageSync(new LambdaMessage([&] { layersProto = dumpDrawingStateProto(traceFlags); }));
     return layersProto;
 }
 
@@ -4931,9 +4921,9 @@
         code == IBinder::SYSPROPS_TRANSACTION) {
         return OK;
     }
-    // Numbers from 1000 to 1034 are currently used for backdoors. The code
+    // Numbers from 1000 to 1036 are currently used for backdoors. The code
     // in onTransact verifies that the user is root, and has access to use SF.
-    if (code >= 1000 && code <= 1035) {
+    if (code >= 1000 && code <= 1036) {
         ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
         return OK;
     }
@@ -5129,20 +5119,12 @@
                 n = data.readInt32();
                 if (n) {
                     ALOGD("LayerTracing enabled");
-                    Mutex::Autolock lock(mStateLock);
-                    mTracingEnabledChanged = true;
-                    mTracing.enable();
+                    mTracingEnabledChanged = mTracing.enable();
                     reply->writeInt32(NO_ERROR);
                 } else {
                     ALOGD("LayerTracing disabled");
-                    bool writeFile = false;
-                    {
-                        Mutex::Autolock lock(mStateLock);
-                        mTracingEnabledChanged = true;
-                        writeFile = mTracing.disable();
-                    }
-
-                    if (writeFile) {
+                    mTracingEnabledChanged = mTracing.disable();
+                    if (mTracingEnabledChanged) {
                         reply->writeInt32(mTracing.writeToFile());
                     } else {
                         reply->writeInt32(NO_ERROR);
@@ -5270,6 +5252,18 @@
                 }
                 return NO_ERROR;
             }
+            case 1036: {
+                if (data.readInt32() > 0) {
+                    status_t result =
+                            acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
+                    if (result != NO_ERROR) {
+                        return result;
+                    }
+                } else {
+                    mDebugFrameRateFlexibilityToken = nullptr;
+                }
+                return NO_ERROR;
+            }
         }
     }
     return err;
@@ -5915,11 +5909,11 @@
         const auto displayId = display->getId();
         LOG_ALWAYS_FATAL_IF(!displayId);
 
-        HWC2::VsyncPeriodChangeConstraints constraints;
+        hal::VsyncPeriodChangeConstraints constraints;
         constraints.desiredTimeNanos = systemTime();
         constraints.seamlessRequired = false;
 
-        HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
+        hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
         if (getHwComposer().setActiveConfigWithConstraints(*displayId,
                                                            policy->defaultConfig.value(),
                                                            constraints, &timeline) < 0) {
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index f3c481a..0f39308 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -33,7 +33,6 @@
 #include <gui/ITransactionCompletedListener.h>
 #include <gui/LayerState.h>
 #include <gui/OccupancyTracker.h>
-#include <hardware/hwcomposer_defs.h>
 #include <input/ISetInputWindowsListener.h>
 #include <layerproto/LayerProtoHeader.h>
 #include <math/mat4.h>
@@ -311,12 +310,12 @@
 
     // main thread function to enable/disable h/w composer event
     void setPrimaryVsyncEnabledInternal(bool enabled);
-    void setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled);
+    void setVsyncEnabledInHWC(DisplayId displayId, hal::Vsync enabled);
 
     // called on the main thread by MessageQueue when an internal message
     // is received
     // TODO: this should be made accessible only to MessageQueue
-    void onMessageReceived(int32_t what);
+    void onMessageReceived(int32_t what, nsecs_t when);
 
     renderengine::RenderEngine& getRenderEngine() const;
 
@@ -517,15 +516,15 @@
     /* ------------------------------------------------------------------------
      * HWC2::ComposerCallback / HWComposer::EventHandler interface
      */
-    void onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId, int64_t timestamp,
-                         std::optional<hwc2_vsync_period_t> vsyncPeriod) override;
-    void onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
-                           HWC2::Connection connection) override;
-    void onRefreshReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId) override;
+    void onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId, int64_t timestamp,
+                         std::optional<hal::VsyncPeriodNanos> vsyncPeriod) override;
+    void onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
+                           hal::Connection connection) override;
+    void onRefreshReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId) override;
     void onVsyncPeriodTimingChangedReceived(
-            int32_t sequenceId, hwc2_display_t display,
-            const hwc_vsync_period_change_timeline_t& updatedTimeline) override;
-    void onSeamlessPossible(int32_t sequenceId, hwc2_display_t display) override;
+            int32_t sequenceId, hal::HWDisplayId display,
+            const hal::VsyncPeriodChangeTimeline& updatedTimeline) override;
+    void onSeamlessPossible(int32_t sequenceId, hal::HWDisplayId display) override;
 
     /* ------------------------------------------------------------------------
      * ISchedulerCallback
@@ -849,7 +848,7 @@
 
     // Populates the expected present time for this frame. For negative offsets, performs a
     // correction using the predicted vsync for the next frame instead.
-    void populateExpectedPresentTime();
+    void populateExpectedPresentTime(nsecs_t now);
 
     /*
      * Display identification
@@ -929,8 +928,7 @@
     void dumpDisplayIdentificationData(std::string& result) const;
     void dumpRawDisplayIdentificationData(const DumpArgs&, std::string& result) const;
     void dumpWideColorInfo(std::string& result) const;
-    LayersProto dumpDrawingStateProto(uint32_t traceFlags = SurfaceTracing::TRACE_ALL,
-                                      const sp<const DisplayDevice>& displayDevice = nullptr) const;
+    LayersProto dumpDrawingStateProto(uint32_t traceFlags) const;
     void dumpOffscreenLayersProto(LayersProto& layersProto,
                                   uint32_t traceFlags = SurfaceTracing::TRACE_ALL) const;
     // Dumps state from HW Composer
@@ -938,7 +936,6 @@
     LayersProto dumpProtoFromMainThread(uint32_t traceFlags = SurfaceTracing::TRACE_ALL)
             EXCLUDES(mStateLock);
     void dumpOffscreenLayers(std::string& result) EXCLUDES(mStateLock);
-    void withTracingLock(std::function<void()> operation) REQUIRES(mStateLock);
 
     bool isLayerTripleBufferingDisabled() const {
         return this->mLayerTripleBufferingDisabled;
@@ -980,9 +977,6 @@
     SortedVector<sp<Layer>> mLayersPendingRemoval;
     bool mTraversalNeededMainThread = false;
 
-    // guards access to the mDrawing state if tracing is enabled.
-    mutable std::mutex mDrawingStateLock;
-
     // global color transform states
     Daltonizer mDaltonizer;
     float mGlobalSaturationFactor = 1.0f;
@@ -1034,8 +1028,8 @@
     BootStage mBootStage = BootStage::BOOTLOADER;
 
     struct HotplugEvent {
-        hwc2_display_t hwcDisplayId;
-        HWC2::Connection connection = HWC2::Connection::Invalid;
+        hal::HWDisplayId hwcDisplayId;
+        hal::Connection connection = hal::Connection::INVALID;
     };
     // protected by mStateLock
     std::vector<HotplugEvent> mPendingHotplugEvents;
@@ -1057,10 +1051,13 @@
     bool mPropagateBackpressure = true;
     bool mPropagateBackpressureClientComposition = false;
     std::unique_ptr<SurfaceInterceptor> mInterceptor;
+
     SurfaceTracing mTracing{*this};
+    std::mutex mTracingLock;
     bool mTracingEnabled = false;
     bool mAddCompositionStateToTrace = false;
-    bool mTracingEnabledChanged GUARDED_BY(mStateLock) = false;
+    std::atomic<bool> mTracingEnabledChanged = false;
+
     const std::shared_ptr<TimeStats> mTimeStats;
     const std::unique_ptr<FrameTracer> mFrameTracer;
     bool mUseHwcVirtualDisplays = false;
@@ -1250,20 +1247,17 @@
     std::unordered_set<Layer*> mOffscreenLayers;
 
     // Flags to capture the state of Vsync in HWC
-    HWC2::Vsync mHWCVsyncState = HWC2::Vsync::Disable;
-    HWC2::Vsync mHWCVsyncPendingState = HWC2::Vsync::Disable;
+    hal::Vsync mHWCVsyncState = hal::Vsync::DISABLE;
+    hal::Vsync mHWCVsyncPendingState = hal::Vsync::DISABLE;
 
     // Fields tracking the current jank event: when it started and how many
     // janky frames there are.
     nsecs_t mMissedFrameJankStart = 0;
     int32_t mMissedFrameJankCount = 0;
 
-    // See updateInputWindowInfo() for details
-    std::atomic<bool> mInputDirty = true;
-    void dirtyInput() { mInputDirty = true; }
-    bool inputDirty() { return mInputDirty; }
-
     int mFrameRateFlexibilityTokenCount = 0;
+
+    sp<IBinder> mDebugFrameRateFlexibilityToken;
 };
 
 } // namespace android
diff --git a/services/surfaceflinger/SurfaceTracing.cpp b/services/surfaceflinger/SurfaceTracing.cpp
index f0b895d..d84ce69 100644
--- a/services/surfaceflinger/SurfaceTracing.cpp
+++ b/services/surfaceflinger/SurfaceTracing.cpp
@@ -33,7 +33,7 @@
 namespace android {
 
 SurfaceTracing::SurfaceTracing(SurfaceFlinger& flinger)
-      : mFlinger(flinger), mSfLock(flinger.mDrawingStateLock) {}
+      : mFlinger(flinger), mSfLock(flinger.mTracingLock) {}
 
 void SurfaceTracing::mainLoop() {
     bool enabled = addFirstEntry();
@@ -44,21 +44,19 @@
 }
 
 bool SurfaceTracing::addFirstEntry() {
-    const auto displayDevice = mFlinger.getDefaultDisplayDevice();
     LayersTraceProto entry;
     {
         std::scoped_lock lock(mSfLock);
-        entry = traceLayersLocked("tracing.enable", displayDevice);
+        entry = traceLayersLocked("tracing.enable");
     }
     return addTraceToBuffer(entry);
 }
 
 LayersTraceProto SurfaceTracing::traceWhenNotified() {
-    const auto displayDevice = mFlinger.getDefaultDisplayDevice();
     std::unique_lock<std::mutex> lock(mSfLock);
     mCanStartTrace.wait(lock);
     android::base::ScopedLockAssertion assumeLock(mSfLock);
-    LayersTraceProto entry = traceLayersLocked(mWhere, displayDevice);
+    LayersTraceProto entry = traceLayersLocked(mWhere);
     mTracingInProgress = false;
     mMissedTraceEntries = 0;
     lock.unlock();
@@ -126,15 +124,17 @@
     }
 }
 
-void SurfaceTracing::enable() {
+bool SurfaceTracing::enable() {
     std::scoped_lock lock(mTraceLock);
 
     if (mEnabled) {
-        return;
+        return false;
     }
+
     mBuffer.reset(mBufferSize);
     mEnabled = true;
     mThread = std::thread(&SurfaceTracing::mainLoop, this);
+    return true;
 }
 
 status_t SurfaceTracing::writeToFile() {
@@ -176,14 +176,13 @@
     mTraceFlags = flags;
 }
 
-LayersTraceProto SurfaceTracing::traceLayersLocked(const char* where,
-                                                   const sp<const DisplayDevice>& displayDevice) {
+LayersTraceProto SurfaceTracing::traceLayersLocked(const char* where) {
     ATRACE_CALL();
 
     LayersTraceProto entry;
     entry.set_elapsed_realtime_nanos(elapsedRealtimeNano());
     entry.set_where(where);
-    LayersProto layers(mFlinger.dumpDrawingStateProto(mTraceFlags, displayDevice));
+    LayersProto layers(mFlinger.dumpDrawingStateProto(mTraceFlags));
 
     if (flagIsSetLocked(SurfaceTracing::TRACE_EXTRA)) {
         mFlinger.dumpOffscreenLayersProto(layers);
diff --git a/services/surfaceflinger/SurfaceTracing.h b/services/surfaceflinger/SurfaceTracing.h
index e90fc4d..f208eb8 100644
--- a/services/surfaceflinger/SurfaceTracing.h
+++ b/services/surfaceflinger/SurfaceTracing.h
@@ -27,8 +27,6 @@
 #include <queue>
 #include <thread>
 
-#include "DisplayDevice.h"
-
 using namespace android::surfaceflinger;
 
 namespace android {
@@ -44,7 +42,7 @@
 class SurfaceTracing {
 public:
     explicit SurfaceTracing(SurfaceFlinger& flinger);
-    void enable();
+    bool enable();
     bool disable();
     status_t writeToFile();
     bool isEnabled() const;
@@ -92,9 +90,7 @@
     void mainLoop();
     bool addFirstEntry();
     LayersTraceProto traceWhenNotified();
-    LayersTraceProto traceLayersLocked(const char* where,
-                                       const sp<const DisplayDevice>& displayDevice)
-            REQUIRES(mSfLock);
+    LayersTraceProto traceLayersLocked(const char* where) REQUIRES(mSfLock);
 
     // Returns true if trace is enabled.
     bool addTraceToBuffer(LayersTraceProto& entry);
diff --git a/services/surfaceflinger/TimeStats/TimeStats.cpp b/services/surfaceflinger/TimeStats/TimeStats.cpp
index 606e137..80fe180 100644
--- a/services/surfaceflinger/TimeStats/TimeStats.cpp
+++ b/services/surfaceflinger/TimeStats/TimeStats.cpp
@@ -290,6 +290,15 @@
     mTimeStats.refreshRateSwitches++;
 }
 
+void TimeStats::incrementCompositionStrategyChanges() {
+    if (!mEnabled.load()) return;
+
+    ATRACE_CALL();
+
+    std::lock_guard<std::mutex> lock(mMutex);
+    mTimeStats.compositionStrategyChanges++;
+}
+
 void TimeStats::recordDisplayEventConnectionCount(int32_t count) {
     if (!mEnabled.load()) return;
 
@@ -844,6 +853,7 @@
     mTimeStats.clientCompositionFrames = 0;
     mTimeStats.clientCompositionReusedFrames = 0;
     mTimeStats.refreshRateSwitches = 0;
+    mTimeStats.compositionStrategyChanges = 0;
     mTimeStats.displayEventConnectionsCount = 0;
     mTimeStats.displayOnTime = 0;
     mTimeStats.presentToPresent.hist.clear();
diff --git a/services/surfaceflinger/TimeStats/TimeStats.h b/services/surfaceflinger/TimeStats/TimeStats.h
index 806b47e..eb48353 100644
--- a/services/surfaceflinger/TimeStats/TimeStats.h
+++ b/services/surfaceflinger/TimeStats/TimeStats.h
@@ -54,6 +54,10 @@
     virtual void incrementClientCompositionReusedFrames() = 0;
     // Increments the number of times the display refresh rate changed.
     virtual void incrementRefreshRateSwitches() = 0;
+    // Increments the number of changes in composition strategy
+    // The intention is to reflect the number of changes between hwc and gpu
+    // composition, where "gpu composition" may also include mixed composition.
+    virtual void incrementCompositionStrategyChanges() = 0;
     // Records the most up-to-date count of display event connections.
     // The stored count will be the maximum ever recoded.
     virtual void recordDisplayEventConnectionCount(int32_t count) = 0;
@@ -218,6 +222,7 @@
     void incrementClientCompositionFrames() override;
     void incrementClientCompositionReusedFrames() override;
     void incrementRefreshRateSwitches() override;
+    void incrementCompositionStrategyChanges() override;
     void recordDisplayEventConnectionCount(int32_t count) override;
 
     void recordFrameDuration(nsecs_t startTime, nsecs_t endTime) override;
diff --git a/services/surfaceflinger/TimeStats/timestatsproto/TimeStatsHelper.cpp b/services/surfaceflinger/TimeStats/timestatsproto/TimeStatsHelper.cpp
index 5305de9..c90b1b8 100644
--- a/services/surfaceflinger/TimeStats/timestatsproto/TimeStatsHelper.cpp
+++ b/services/surfaceflinger/TimeStats/timestatsproto/TimeStatsHelper.cpp
@@ -106,6 +106,7 @@
     StringAppendF(&result, "clientCompositionFrames = %d\n", clientCompositionFrames);
     StringAppendF(&result, "clientCompositionReusedFrames = %d\n", clientCompositionReusedFrames);
     StringAppendF(&result, "refreshRateSwitches = %d\n", refreshRateSwitches);
+    StringAppendF(&result, "compositionStrategyChanges = %d\n", compositionStrategyChanges);
     StringAppendF(&result, "displayOnTime = %" PRId64 " ms\n", displayOnTime);
     StringAppendF(&result, "displayConfigStats is as below:\n");
     for (const auto& [fps, duration] : refreshRateStats) {
diff --git a/services/surfaceflinger/TimeStats/timestatsproto/include/timestatsproto/TimeStatsHelper.h b/services/surfaceflinger/TimeStats/timestatsproto/include/timestatsproto/TimeStatsHelper.h
index afb98e0..0c75f96 100644
--- a/services/surfaceflinger/TimeStats/timestatsproto/include/timestatsproto/TimeStatsHelper.h
+++ b/services/surfaceflinger/TimeStats/timestatsproto/include/timestatsproto/TimeStatsHelper.h
@@ -63,6 +63,7 @@
         int32_t clientCompositionFrames = 0;
         int32_t clientCompositionReusedFrames = 0;
         int32_t refreshRateSwitches = 0;
+        int32_t compositionStrategyChanges = 0;
         int32_t displayEventConnectionsCount = 0;
         int64_t displayOnTime = 0;
         Histogram presentToPresent;
diff --git a/services/surfaceflinger/tests/LayerTransactionTest.h b/services/surfaceflinger/tests/LayerTransactionTest.h
index 40ec502..f3e11d8 100644
--- a/services/surfaceflinger/tests/LayerTransactionTest.h
+++ b/services/surfaceflinger/tests/LayerTransactionTest.h
@@ -19,7 +19,6 @@
 #include <gtest/gtest.h>
 #include <gui/ISurfaceComposer.h>
 #include <gui/SurfaceComposerClient.h>
-#include <hardware/hwcomposer_defs.h>
 #include <private/gui/ComposerService.h>
 #include <ui/DisplayConfig.h>
 
diff --git a/services/surfaceflinger/tests/fakehwc/FakeComposerClient.h b/services/surfaceflinger/tests/fakehwc/FakeComposerClient.h
index 5240b72..600e765 100644
--- a/services/surfaceflinger/tests/fakehwc/FakeComposerClient.h
+++ b/services/surfaceflinger/tests/fakehwc/FakeComposerClient.h
@@ -16,24 +16,16 @@
 
 #pragma once
 
-#define HWC2_USE_CPP11
-#define HWC2_INCLUDE_STRINGIFICATION
+#include <chrono>
+
 #include <composer-hal/2.1/ComposerClient.h>
 #include <composer-hal/2.2/ComposerClient.h>
 #include <composer-hal/2.3/ComposerClient.h>
 #include <composer-hal/2.4/ComposerClient.h>
-#undef HWC2_USE_CPP11
-#undef HWC2_INCLUDE_STRINGIFICATION
-#include "RenderState.h"
-
-#include "MockComposerHal.h"
-
-// Needed for display type/ID enums
-#include <hardware/hwcomposer_defs.h>
-
 #include <utils/Condition.h>
 
-#include <chrono>
+#include "MockComposerHal.h"
+#include "RenderState.h"
 
 using namespace android::hardware::graphics::common;
 using namespace android::hardware::graphics::composer;
diff --git a/services/surfaceflinger/tests/fakehwc/FakeComposerUtils.h b/services/surfaceflinger/tests/fakehwc/FakeComposerUtils.h
index 09a2a89..383a111 100644
--- a/services/surfaceflinger/tests/fakehwc/FakeComposerUtils.h
+++ b/services/surfaceflinger/tests/fakehwc/FakeComposerUtils.h
@@ -19,11 +19,7 @@
 #include "FakeComposerClient.h"
 
 #include <gui/SurfaceComposerClient.h>
-
-#include <hardware/hwcomposer_defs.h>
-
 #include <log/log.h>
-
 #include <gtest/gtest.h>
 
 // clang-format off
diff --git a/services/surfaceflinger/tests/fakehwc/RenderState.h b/services/surfaceflinger/tests/fakehwc/RenderState.h
index 0059289..40193f2 100644
--- a/services/surfaceflinger/tests/fakehwc/RenderState.h
+++ b/services/surfaceflinger/tests/fakehwc/RenderState.h
@@ -16,8 +16,6 @@
 
 #pragma once
 
-#include <hardware/hwcomposer2.h>
-
 #include <vector>
 
 namespace sftest {
diff --git a/services/surfaceflinger/tests/unittests/CompositionTest.cpp b/services/surfaceflinger/tests/unittests/CompositionTest.cpp
index 2dcaf63..1aa67b4 100644
--- a/services/surfaceflinger/tests/unittests/CompositionTest.cpp
+++ b/services/surfaceflinger/tests/unittests/CompositionTest.cpp
@@ -50,6 +50,8 @@
 namespace android {
 namespace {
 
+namespace hal = android::hardware::graphics::composer::hal;
+
 using testing::_;
 using testing::AtLeast;
 using testing::Between;
@@ -73,8 +75,8 @@
 using FakeHwcDisplayInjector = TestableSurfaceFlinger::FakeHwcDisplayInjector;
 using FakeDisplayDeviceInjector = TestableSurfaceFlinger::FakeDisplayDeviceInjector;
 
-constexpr hwc2_display_t HWC_DISPLAY = FakeHwcDisplayInjector::DEFAULT_HWC_DISPLAY_ID;
-constexpr hwc2_layer_t HWC_LAYER = 5000;
+constexpr hal::HWDisplayId HWC_DISPLAY = FakeHwcDisplayInjector::DEFAULT_HWC_DISPLAY_ID;
+constexpr hal::HWLayerId HWC_LAYER = 5000;
 constexpr Transform DEFAULT_TRANSFORM = static_cast<Transform>(0);
 
 constexpr DisplayId DEFAULT_DISPLAY_ID = DisplayId{42};
@@ -141,10 +143,10 @@
 
         auto primaryDispSync = std::make_unique<mock::DispSync>();
 
-        EXPECT_CALL(*primaryDispSync, computeNextRefresh(0)).WillRepeatedly(Return(0));
+        EXPECT_CALL(*primaryDispSync, computeNextRefresh(0, _)).WillRepeatedly(Return(0));
         EXPECT_CALL(*primaryDispSync, getPeriod())
                 .WillRepeatedly(Return(FakeHwcDisplayInjector::DEFAULT_REFRESH_RATE));
-        EXPECT_CALL(*primaryDispSync, expectedPresentTime()).WillRepeatedly(Return(0));
+        EXPECT_CALL(*primaryDispSync, expectedPresentTime(_)).WillRepeatedly(Return(0));
 
         mFlinger.setupScheduler(std::move(primaryDispSync),
                                 std::make_unique<mock::EventControlThread>(),
@@ -170,7 +172,7 @@
     template <typename Case>
     void captureScreenComposition();
 
-    std::unordered_set<HWC2::Capability> mDefaultCapabilities = {HWC2::Capability::SidebandStream};
+    std::unordered_set<hal::Capability> mDefaultCapabilities = {hal::Capability::SIDEBAND_STREAM};
 
     bool mDisplayOff = false;
     TestableSurfaceFlinger mFlinger;
@@ -272,8 +274,7 @@
                                          Derived::INIT_POWER_MODE)))
                 .WillOnce(Return(Error::NONE));
 
-        FakeHwcDisplayInjector(DEFAULT_DISPLAY_ID, HWC2::DisplayType::Physical,
-                               true /* isPrimary */)
+        FakeHwcDisplayInjector(DEFAULT_DISPLAY_ID, hal::DisplayType::PHYSICAL, true /* isPrimary */)
                 .setCapabilities(&test->mDefaultCapabilities)
                 .setPowerMode(Derived::INIT_POWER_MODE)
                 .inject(&test->mFlinger, test->mComposer);
@@ -989,7 +990,7 @@
 
 template <IComposerClient::Composition CompositionType>
 struct KeepCompositionTypeVariant {
-    static constexpr HWC2::Composition TYPE = static_cast<HWC2::Composition>(CompositionType);
+    static constexpr hal::Composition TYPE = CompositionType;
 
     static void setupHwcSetCallExpectations(CompositionTest* test) {
         if (!test->mDisplayOff) {
@@ -1007,7 +1008,7 @@
 template <IComposerClient::Composition InitialCompositionType,
           IComposerClient::Composition FinalCompositionType>
 struct ChangeCompositionTypeVariant {
-    static constexpr HWC2::Composition TYPE = static_cast<HWC2::Composition>(FinalCompositionType);
+    static constexpr hal::Composition TYPE = FinalCompositionType;
 
     static void setupHwcSetCallExpectations(CompositionTest* test) {
         if (!test->mDisplayOff) {
diff --git a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
index cd11409..3bc7008 100644
--- a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
+++ b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
@@ -55,6 +55,8 @@
 namespace android {
 namespace {
 
+namespace hal = android::hardware::graphics::composer::hal;
+
 using testing::_;
 using testing::AnyNumber;
 using testing::DoAll;
@@ -65,13 +67,18 @@
 using testing::SetArgPointee;
 using testing::StrictMock;
 
-using android::Hwc2::ColorMode;
-using android::Hwc2::Error;
-using android::Hwc2::Hdr;
-using android::Hwc2::IComposer;
-using android::Hwc2::IComposerClient;
-using android::Hwc2::PerFrameMetadataKey;
-using android::Hwc2::RenderIntent;
+using hal::ColorMode;
+using hal::Connection;
+using hal::DisplayCapability;
+using hal::DisplayType;
+using hal::Error;
+using hal::Hdr;
+using hal::HWDisplayId;
+using hal::IComposer;
+using hal::IComposerClient;
+using hal::PerFrameMetadataKey;
+using hal::PowerMode;
+using hal::RenderIntent;
 
 using FakeDisplayDeviceInjector = TestableSurfaceFlinger::FakeDisplayDeviceInjector;
 using FakeHwcDisplayInjector = TestableSurfaceFlinger::FakeHwcDisplayInjector;
@@ -120,7 +127,7 @@
     // --------------------------------------------------------------------
     // Postcondition helpers
 
-    bool hasPhysicalHwcDisplay(hwc2_display_t hwcDisplayId);
+    bool hasPhysicalHwcDisplay(HWDisplayId hwcDisplayId);
     bool hasTransactionFlagSet(int flag);
     bool hasDisplayDevice(sp<IBinder> displayToken);
     sp<DisplayDevice> getDisplayDevice(sp<IBinder> displayToken);
@@ -246,7 +253,7 @@
     constexpr DisplayId DEFAULT_DISPLAY_ID = DisplayId{777};
     constexpr int DEFAULT_DISPLAY_WIDTH = 1080;
     constexpr int DEFAULT_DISPLAY_HEIGHT = 1920;
-    constexpr hwc2_display_t DEFAULT_DISPLAY_HWC_DISPLAY_ID = 0;
+    constexpr HWDisplayId DEFAULT_DISPLAY_HWC_DISPLAY_ID = 0;
 
     // The DisplayDevice is required to have a framebuffer (behind the
     // ANativeWindow interface) which uses the actual hardware display
@@ -285,7 +292,7 @@
     return displayDevice;
 }
 
-bool DisplayTransactionTest::hasPhysicalHwcDisplay(hwc2_display_t hwcDisplayId) {
+bool DisplayTransactionTest::hasPhysicalHwcDisplay(HWDisplayId hwcDisplayId) {
     return mFlinger.mutableHwcPhysicalDisplayIdMap().count(hwcDisplayId) == 1;
 }
 
@@ -376,19 +383,19 @@
 
 template <typename>
 struct HwcDisplayIdGetter {
-    static constexpr std::optional<hwc2_display_t> value;
+    static constexpr std::optional<HWDisplayId> value;
 };
 
-constexpr hwc2_display_t HWC_VIRTUAL_DISPLAY_HWC_DISPLAY_ID = 1010;
+constexpr HWDisplayId HWC_VIRTUAL_DISPLAY_HWC_DISPLAY_ID = 1010;
 
 template <DisplayId::Type displayId>
 struct HwcDisplayIdGetter<VirtualDisplayId<displayId>> {
-    static constexpr std::optional<hwc2_display_t> value = HWC_VIRTUAL_DISPLAY_HWC_DISPLAY_ID;
+    static constexpr std::optional<HWDisplayId> value = HWC_VIRTUAL_DISPLAY_HWC_DISPLAY_ID;
 };
 
 template <typename PhysicalDisplay>
 struct HwcDisplayIdGetter<PhysicalDisplayId<PhysicalDisplay>> {
-    static constexpr std::optional<hwc2_display_t> value = PhysicalDisplay::HWC_DISPLAY_ID;
+    static constexpr std::optional<HWDisplayId> value = PhysicalDisplay::HWC_DISPLAY_ID;
 };
 
 // DisplayIdType can be:
@@ -497,21 +504,20 @@
     }
 };
 
-template <hwc2_display_t hwcDisplayId, HWC2::DisplayType hwcDisplayType, typename DisplayVariant,
+template <HWDisplayId hwcDisplayId, DisplayType hwcDisplayType, typename DisplayVariant,
           typename PhysicalDisplay = void>
 struct HwcDisplayVariant {
     // The display id supplied by the HWC
-    static constexpr hwc2_display_t HWC_DISPLAY_ID = hwcDisplayId;
+    static constexpr HWDisplayId HWC_DISPLAY_ID = hwcDisplayId;
 
     // The HWC display type
-    static constexpr HWC2::DisplayType HWC_DISPLAY_TYPE = hwcDisplayType;
+    static constexpr DisplayType HWC_DISPLAY_TYPE = hwcDisplayType;
 
     // The HWC active configuration id
     static constexpr int HWC_ACTIVE_CONFIG_ID = 2001;
     static constexpr int INIT_POWER_MODE = HWC_POWER_MODE_NORMAL;
 
-    static void injectPendingHotplugEvent(DisplayTransactionTest* test,
-                                          HWC2::Connection connection) {
+    static void injectPendingHotplugEvent(DisplayTransactionTest* test, Connection connection) {
         test->mFlinger.mutablePendingHotplugEvents().emplace_back(
                 HotplugEvent{HWC_DISPLAY_ID, connection});
     }
@@ -533,11 +539,10 @@
     // Called by tests to inject a HWC display setup
     static void injectHwcDisplay(DisplayTransactionTest* test) {
         EXPECT_CALL(*test->mComposer, getDisplayCapabilities(HWC_DISPLAY_ID, _))
-                .WillOnce(DoAll(SetArgPointee<1>(std::vector<Hwc2::DisplayCapability>({})),
+                .WillOnce(DoAll(SetArgPointee<1>(std::vector<DisplayCapability>({})),
                                 Return(Error::NONE)));
         EXPECT_CALL(*test->mComposer,
-                    setPowerMode(HWC_DISPLAY_ID,
-                                 static_cast<Hwc2::IComposerClient::PowerMode>(INIT_POWER_MODE)))
+                    setPowerMode(HWC_DISPLAY_ID, static_cast<PowerMode>(INIT_POWER_MODE)))
                 .WillOnce(Return(Error::NONE));
         injectHwcDisplayWithNoDefaultCapabilities(test);
     }
@@ -568,10 +573,10 @@
                 : IComposerClient::DisplayConnectionType::EXTERNAL;
 
         EXPECT_CALL(*test->mComposer, getDisplayConnectionType(HWC_DISPLAY_ID, _))
-                .WillOnce(
-                        DoAll(SetArgPointee<1>(CONNECTION_TYPE), Return(Hwc2::V2_4::Error::NONE)));
+                .WillOnce(DoAll(SetArgPointee<1>(CONNECTION_TYPE), Return(hal::V2_4::Error::NONE)));
 
-        EXPECT_CALL(*test->mComposer, setClientTargetSlotCount(_)).WillOnce(Return(Error::NONE));
+        EXPECT_CALL(*test->mComposer, setClientTargetSlotCount(_))
+                .WillOnce(Return(hal::Error::NONE));
         EXPECT_CALL(*test->mComposer, getDisplayConfigs(HWC_DISPLAY_ID, _))
                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<unsigned>{HWC_ACTIVE_CONFIG_ID}),
                                 Return(Error::NONE)));
@@ -626,7 +631,7 @@
 struct PhysicalDisplayVariant
       : DisplayVariant<PhysicalDisplayId<PhysicalDisplay>, width, height, critical, Async::FALSE,
                        Secure::TRUE, PhysicalDisplay::PRIMARY, GRALLOC_USAGE_PHYSICAL_DISPLAY>,
-        HwcDisplayVariant<PhysicalDisplay::HWC_DISPLAY_ID, HWC2::DisplayType::Physical,
+        HwcDisplayVariant<PhysicalDisplay::HWC_DISPLAY_ID, DisplayType::PHYSICAL,
                           DisplayVariant<PhysicalDisplayId<PhysicalDisplay>, width, height,
                                          critical, Async::FALSE, Secure::TRUE,
                                          PhysicalDisplay::PRIMARY, GRALLOC_USAGE_PHYSICAL_DISPLAY>,
@@ -637,7 +642,7 @@
     static constexpr auto CONNECTION_TYPE = DisplayConnectionType::Internal;
     static constexpr Primary PRIMARY = Primary::TRUE;
     static constexpr uint8_t PORT = 255;
-    static constexpr hwc2_display_t HWC_DISPLAY_ID = 1001;
+    static constexpr HWDisplayId HWC_DISPLAY_ID = 1001;
     static constexpr bool HAS_IDENTIFICATION_DATA = hasIdentificationData;
     static constexpr auto GET_IDENTIFICATION_DATA = getInternalEdid;
 };
@@ -647,7 +652,7 @@
     static constexpr auto CONNECTION_TYPE = DisplayConnectionType::External;
     static constexpr Primary PRIMARY = Primary::FALSE;
     static constexpr uint8_t PORT = 254;
-    static constexpr hwc2_display_t HWC_DISPLAY_ID = 1002;
+    static constexpr HWDisplayId HWC_DISPLAY_ID = 1002;
     static constexpr bool HAS_IDENTIFICATION_DATA = hasIdentificationData;
     static constexpr auto GET_IDENTIFICATION_DATA = getExternalEdid;
 };
@@ -655,7 +660,7 @@
 struct TertiaryDisplay {
     static constexpr Primary PRIMARY = Primary::FALSE;
     static constexpr uint8_t PORT = 253;
-    static constexpr hwc2_display_t HWC_DISPLAY_ID = 1003;
+    static constexpr HWDisplayId HWC_DISPLAY_ID = 1003;
     static constexpr auto GET_IDENTIFICATION_DATA = getExternalEdid;
 };
 
@@ -716,7 +721,7 @@
       : DisplayVariant<VirtualDisplayId<42>, width, height, Critical::FALSE, Async::TRUE, secure,
                        Primary::FALSE, GRALLOC_USAGE_HWC_VIRTUAL_DISPLAY>,
         HwcDisplayVariant<
-                HWC_VIRTUAL_DISPLAY_HWC_DISPLAY_ID, HWC2::DisplayType::Virtual,
+                HWC_VIRTUAL_DISPLAY_HWC_DISPLAY_ID, DisplayType::VIRTUAL,
                 DisplayVariant<VirtualDisplayId<42>, width, height, Critical::FALSE, Async::TRUE,
                                secure, Primary::FALSE, GRALLOC_USAGE_HWC_VIRTUAL_DISPLAY>> {
     using Base = DisplayVariant<VirtualDisplayId<42>, width, height, Critical::FALSE, Async::TRUE,
@@ -1046,8 +1051,8 @@
 
 TEST_F(DisplayTransactionTest, hotplugEnqueuesEventsForDisplayTransaction) {
     constexpr int currentSequenceId = 123;
-    constexpr hwc2_display_t hwcDisplayId1 = 456;
-    constexpr hwc2_display_t hwcDisplayId2 = 654;
+    constexpr HWDisplayId hwcDisplayId1 = 456;
+    constexpr HWDisplayId hwcDisplayId2 = 654;
 
     // --------------------------------------------------------------------
     // Preconditions
@@ -1070,8 +1075,8 @@
     // Invocation
 
     // Simulate two hotplug events (a connect and a disconnect)
-    mFlinger.onHotplugReceived(currentSequenceId, hwcDisplayId1, HWC2::Connection::Connected);
-    mFlinger.onHotplugReceived(currentSequenceId, hwcDisplayId2, HWC2::Connection::Disconnected);
+    mFlinger.onHotplugReceived(currentSequenceId, hwcDisplayId1, Connection::CONNECTED);
+    mFlinger.onHotplugReceived(currentSequenceId, hwcDisplayId2, Connection::DISCONNECTED);
 
     // --------------------------------------------------------------------
     // Postconditions
@@ -1083,15 +1088,15 @@
     const auto& pendingEvents = mFlinger.mutablePendingHotplugEvents();
     ASSERT_EQ(2u, pendingEvents.size());
     EXPECT_EQ(hwcDisplayId1, pendingEvents[0].hwcDisplayId);
-    EXPECT_EQ(HWC2::Connection::Connected, pendingEvents[0].connection);
+    EXPECT_EQ(Connection::CONNECTED, pendingEvents[0].connection);
     EXPECT_EQ(hwcDisplayId2, pendingEvents[1].hwcDisplayId);
-    EXPECT_EQ(HWC2::Connection::Disconnected, pendingEvents[1].connection);
+    EXPECT_EQ(Connection::DISCONNECTED, pendingEvents[1].connection);
 }
 
 TEST_F(DisplayTransactionTest, hotplugDiscardsUnexpectedEvents) {
     constexpr int currentSequenceId = 123;
     constexpr int otherSequenceId = 321;
-    constexpr hwc2_display_t displayId = 456;
+    constexpr HWDisplayId displayId = 456;
 
     // --------------------------------------------------------------------
     // Preconditions
@@ -1113,7 +1118,7 @@
     // Invocation
 
     // Call with an unexpected sequence id
-    mFlinger.onHotplugReceived(otherSequenceId, displayId, HWC2::Connection::Invalid);
+    mFlinger.onHotplugReceived(otherSequenceId, displayId, Connection::INVALID);
 
     // --------------------------------------------------------------------
     // Postconditions
@@ -1127,7 +1132,7 @@
 
 TEST_F(DisplayTransactionTest, hotplugProcessesEnqueuedEventsIfCalledOnMainThread) {
     constexpr int currentSequenceId = 123;
-    constexpr hwc2_display_t displayId1 = 456;
+    constexpr HWDisplayId displayId1 = 456;
 
     // --------------------------------------------------------------------
     // Note:
@@ -1161,7 +1166,7 @@
     // Simulate a disconnect on a display id that is not connected. This should
     // be enqueued by onHotplugReceived(), and dequeued by
     // processDisplayHotplugEventsLocked(), but then ignored as invalid.
-    mFlinger.onHotplugReceived(currentSequenceId, displayId1, HWC2::Connection::Disconnected);
+    mFlinger.onHotplugReceived(currentSequenceId, displayId1, Connection::DISCONNECTED);
 
     // --------------------------------------------------------------------
     // Postconditions
@@ -2010,7 +2015,7 @@
     setupCommonPreconditions<Case>();
 
     // A hotplug connect event is enqueued for a display
-    Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Connected);
+    Case::Display::injectPendingHotplugEvent(this, Connection::CONNECTED);
 
     // --------------------------------------------------------------------
     // Call Expectations
@@ -2046,7 +2051,7 @@
     setupCommonPreconditions<Case>();
 
     // A hotplug connect event is enqueued for a display
-    Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Connected);
+    Case::Display::injectPendingHotplugEvent(this, Connection::CONNECTED);
 
     // --------------------------------------------------------------------
     // Invocation
@@ -2068,7 +2073,7 @@
     setupCommonPreconditions<Case>();
 
     // A hotplug disconnect event is enqueued for a display
-    Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Disconnected);
+    Case::Display::injectPendingHotplugEvent(this, Connection::DISCONNECTED);
 
     // The display is already completely set up.
     Case::Display::injectHwcDisplay(this);
@@ -2166,9 +2171,9 @@
     setupCommonPreconditions<Case>();
 
     // A hotplug connect event is enqueued for a display
-    Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Connected);
+    Case::Display::injectPendingHotplugEvent(this, Connection::CONNECTED);
     // A hotplug disconnect event is also enqueued for the same display
-    Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Disconnected);
+    Case::Display::injectPendingHotplugEvent(this, Connection::DISCONNECTED);
 
     // --------------------------------------------------------------------
     // Call Expectations
@@ -2214,9 +2219,9 @@
     existing.inject();
 
     // A hotplug disconnect event is enqueued for a display
-    Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Disconnected);
+    Case::Display::injectPendingHotplugEvent(this, Connection::DISCONNECTED);
     // A hotplug connect event is also enqueued for the same display
-    Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Connected);
+    Case::Display::injectPendingHotplugEvent(this, Connection::CONNECTED);
 
     // --------------------------------------------------------------------
     // Call Expectations
@@ -3093,7 +3098,7 @@
     // processing.
     EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
 
-    EXPECT_CALL(*mPrimaryDispSync, expectedPresentTime()).WillRepeatedly(Return(0));
+    EXPECT_CALL(*mPrimaryDispSync, expectedPresentTime(_)).WillRepeatedly(Return(0));
 
     // --------------------------------------------------------------------
     // Invocation
@@ -3156,8 +3161,8 @@
 
     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
         EXPECT_CALL(*test->mComposer, getDisplayCapabilities(Display::HWC_DISPLAY_ID, _))
-                .WillOnce(DoAll(SetArgPointee<1>(std::vector<Hwc2::DisplayCapability>(
-                                        {Hwc2::DisplayCapability::DOZE})),
+                .WillOnce(DoAll(SetArgPointee<1>(
+                                        std::vector<DisplayCapability>({DisplayCapability::DOZE})),
                                 Return(Error::NONE)));
     }
 };
@@ -3173,7 +3178,7 @@
 
     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
         EXPECT_CALL(*test->mComposer, getDisplayCapabilities(Display::HWC_DISPLAY_ID, _))
-                .WillOnce(DoAll(SetArgPointee<1>(std::vector<Hwc2::DisplayCapability>({})),
+                .WillOnce(DoAll(SetArgPointee<1>(std::vector<DisplayCapability>({})),
                                 Return(Error::NONE)));
     }
 };
diff --git a/services/surfaceflinger/tests/unittests/HWComposerTest.cpp b/services/surfaceflinger/tests/unittests/HWComposerTest.cpp
index c6fe205..91b304c 100644
--- a/services/surfaceflinger/tests/unittests/HWComposerTest.cpp
+++ b/services/surfaceflinger/tests/unittests/HWComposerTest.cpp
@@ -36,6 +36,8 @@
 namespace android {
 namespace {
 
+namespace hal = android::hardware::graphics::composer::hal;
+
 using ::testing::_;
 using ::testing::DoAll;
 using ::testing::ElementsAreArray;
@@ -47,15 +49,15 @@
     ~MockHWC2ComposerCallback() = default;
 
     MOCK_METHOD3(onHotplugReceived,
-                 void(int32_t sequenceId, hwc2_display_t display, HWC2::Connection connection));
-    MOCK_METHOD2(onRefreshReceived, void(int32_t sequenceId, hwc2_display_t display));
+                 void(int32_t sequenceId, hal::HWDisplayId display, hal::Connection connection));
+    MOCK_METHOD2(onRefreshReceived, void(int32_t sequenceId, hal::HWDisplayId display));
     MOCK_METHOD4(onVsyncReceived,
-                 void(int32_t sequenceId, hwc2_display_t display, int64_t timestamp,
-                      std::optional<hwc2_vsync_period_t> vsyncPeriod));
+                 void(int32_t sequenceId, hal::HWDisplayId display, int64_t timestamp,
+                      std::optional<hal::VsyncPeriodNanos> vsyncPeriod));
     MOCK_METHOD3(onVsyncPeriodTimingChangedReceived,
-                 void(int32_t sequenceId, hwc2_display_t display,
-                      const hwc_vsync_period_change_timeline_t& updatedTimeline));
-    MOCK_METHOD2(onSeamlessPossible, void(int32_t sequenceId, hwc2_display_t display));
+                 void(int32_t sequenceId, hal::HWDisplayId display,
+                      const hal::VsyncPeriodChangeTimeline& updatedTimeline));
+    MOCK_METHOD2(onSeamlessPossible, void(int32_t sequenceId, hal::HWDisplayId display));
 };
 
 struct HWComposerTest : public testing::Test {
@@ -73,14 +75,12 @@
     constexpr bool kMetadata2Mandatory = true;
 
     EXPECT_CALL(*mHal, getMaxVirtualDisplayCount()).WillOnce(Return(0));
-    EXPECT_CALL(*mHal, getCapabilities())
-            .WillOnce(Return(std::vector<Hwc2::IComposer::Capability>{}));
+    EXPECT_CALL(*mHal, getCapabilities()).WillOnce(Return(std::vector<hal::Capability>{}));
     EXPECT_CALL(*mHal, getLayerGenericMetadataKeys(_))
-            .WillOnce(DoAll(SetArgPointee<0>(
-                                    std::vector<Hwc2::IComposerClient::LayerGenericMetadataKey>{
-                                            {kMetadata1Name, kMetadata1Mandatory},
-                                            {kMetadata2Name, kMetadata2Mandatory},
-                                    }),
+            .WillOnce(DoAll(SetArgPointee<0>(std::vector<hal::LayerGenericMetadataKey>{
+                                    {kMetadata1Name, kMetadata1Mandatory},
+                                    {kMetadata2Name, kMetadata2Mandatory},
+                            }),
                             Return(hardware::graphics::composer::V2_4::Error::NONE)));
     EXPECT_CALL(*mHal, registerCallback(_));
     EXPECT_CALL(*mHal, isVsyncPeriodSwitchSupported()).WillOnce(Return(false));
@@ -98,8 +98,7 @@
 
 TEST_F(HWComposerSetConfigurationTest, handlesUnsupportedCallToGetLayerGenericMetadataKeys) {
     EXPECT_CALL(*mHal, getMaxVirtualDisplayCount()).WillOnce(Return(0));
-    EXPECT_CALL(*mHal, getCapabilities())
-            .WillOnce(Return(std::vector<Hwc2::IComposer::Capability>{}));
+    EXPECT_CALL(*mHal, getCapabilities()).WillOnce(Return(std::vector<hal::Capability>{}));
     EXPECT_CALL(*mHal, getLayerGenericMetadataKeys(_))
             .WillOnce(Return(hardware::graphics::composer::V2_4::Error::UNSUPPORTED));
     EXPECT_CALL(*mHal, registerCallback(_));
@@ -113,16 +112,16 @@
 }
 
 struct HWComposerLayerTest : public testing::Test {
-    static constexpr hwc2_display_t kDisplayId = static_cast<hwc2_display_t>(1001);
-    static constexpr hwc2_layer_t kLayerId = static_cast<hwc2_layer_t>(1002);
+    static constexpr hal::HWDisplayId kDisplayId = static_cast<hal::HWDisplayId>(1001);
+    static constexpr hal::HWLayerId kLayerId = static_cast<hal::HWLayerId>(1002);
 
-    HWComposerLayerTest(const std::unordered_set<HWC2::Capability>& capabilities)
+    HWComposerLayerTest(const std::unordered_set<hal::Capability>& capabilities)
           : mCapabilies(capabilities) {}
 
     ~HWComposerLayerTest() override { EXPECT_CALL(*mHal, destroyLayer(kDisplayId, kLayerId)); }
 
     std::unique_ptr<Hwc2::mock::Composer> mHal{new StrictMock<Hwc2::mock::Composer>()};
-    const std::unordered_set<HWC2::Capability> mCapabilies;
+    const std::unordered_set<hal::Capability> mCapabilies;
     HWC2::impl::Layer mLayer{*mHal, mCapabilies, kDisplayId, kLayerId};
 };
 
@@ -159,7 +158,7 @@
     auto result = mLayer.setLayerGenericMetadata(kLayerGenericMetadata1Name,
                                                  kLayerGenericMetadata1Mandatory,
                                                  kLayerGenericMetadata1Value);
-    EXPECT_EQ(HWC2::Error::None, result);
+    EXPECT_EQ(hal::Error::NONE, result);
 
     EXPECT_CALL(*mHal,
                 setLayerGenericMetadata(kDisplayId, kLayerId, kLayerGenericMetadata2Name,
@@ -169,7 +168,7 @@
     result = mLayer.setLayerGenericMetadata(kLayerGenericMetadata2Name,
                                             kLayerGenericMetadata2Mandatory,
                                             kLayerGenericMetadata2Value);
-    EXPECT_EQ(HWC2::Error::Unsupported, result);
+    EXPECT_EQ(hal::Error::UNSUPPORTED, result);
 }
 
 } // namespace
diff --git a/services/surfaceflinger/tests/unittests/LayerHistoryTestV2.cpp b/services/surfaceflinger/tests/unittests/LayerHistoryTestV2.cpp
index 71e37a8..6fca673 100644
--- a/services/surfaceflinger/tests/unittests/LayerHistoryTestV2.cpp
+++ b/services/surfaceflinger/tests/unittests/LayerHistoryTestV2.cpp
@@ -270,12 +270,12 @@
     EXPECT_EQ(1, activeLayerCount());
     EXPECT_EQ(1, frequentLayerCount(time));
 
-    // layer became inactive
+    // layer became inactive, but the vote stays
     setLayerInfoVote(layer.get(), LayerHistory::LayerVoteType::Heuristic);
     time += MAX_ACTIVE_LAYER_PERIOD_NS.count();
-    ASSERT_TRUE(history().summarize(time).empty());
-    // TODO: activeLayerCount() should be 0 but it is 1 since getFrameRateForLayerTree() returns a
-    // value > 0
+    ASSERT_EQ(1, history().summarize(time).size());
+    EXPECT_EQ(LayerHistory::LayerVoteType::ExplicitDefault, history().summarize(time)[0].vote);
+    EXPECT_FLOAT_EQ(73.4f, history().summarize(time)[0].desiredRefreshRate);
     EXPECT_EQ(1, activeLayerCount());
     EXPECT_EQ(0, frequentLayerCount(time));
 }
@@ -303,12 +303,13 @@
     EXPECT_EQ(1, activeLayerCount());
     EXPECT_EQ(1, frequentLayerCount(time));
 
-    // layer became inactive
+    // layer became inactive, but the vote stays
     setLayerInfoVote(layer.get(), LayerHistory::LayerVoteType::Heuristic);
     time += MAX_ACTIVE_LAYER_PERIOD_NS.count();
-    ASSERT_TRUE(history().summarize(time).empty());
-    // TODO: activeLayerCount() should be 0 but it is 1 since getFrameRateForLayerTree() returns a
-    // value > 0
+    ASSERT_EQ(1, history().summarize(time).size());
+    EXPECT_EQ(LayerHistory::LayerVoteType::ExplicitExactOrMultiple,
+              history().summarize(time)[0].vote);
+    EXPECT_FLOAT_EQ(73.4f, history().summarize(time)[0].desiredRefreshRate);
     EXPECT_EQ(1, activeLayerCount());
     EXPECT_EQ(0, frequentLayerCount(time));
 }
diff --git a/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp b/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
index 1b8f11b..2ceb89c 100644
--- a/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
+++ b/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
@@ -32,6 +32,8 @@
 namespace android {
 namespace scheduler {
 
+namespace hal = android::hardware::graphics::composer::hal;
+
 using RefreshRate = RefreshRateConfigs::RefreshRate;
 using LayerVoteType = RefreshRateConfigs::LayerVoteType;
 using LayerRequirement = RefreshRateConfigs::LayerRequirement;
@@ -142,7 +144,7 @@
 std::shared_ptr<const HWC2::Display::Config> RefreshRateConfigsTest::createConfig(
         HwcConfigIndexType configId, int32_t configGroup, int64_t vsyncPeriod, int32_t hight,
         int32_t width) {
-    return HWC2::Display::Config::Builder(mDisplay, hwc2_config_t(configId.value()))
+    return HWC2::Display::Config::Builder(mDisplay, hal::HWConfigId(configId.value()))
             .setVsyncPeriod(int32_t(vsyncPeriod))
             .setConfigGroup(configGroup)
             .setHeight(hight)
diff --git a/services/surfaceflinger/tests/unittests/RefreshRateSelectionTest.cpp b/services/surfaceflinger/tests/unittests/RefreshRateSelectionTest.cpp
index 18b1063..43b8e01 100644
--- a/services/surfaceflinger/tests/unittests/RefreshRateSelectionTest.cpp
+++ b/services/surfaceflinger/tests/unittests/RefreshRateSelectionTest.cpp
@@ -142,10 +142,10 @@
 
     auto primaryDispSync = std::make_unique<mock::DispSync>();
 
-    EXPECT_CALL(*primaryDispSync, computeNextRefresh(0)).WillRepeatedly(Return(0));
+    EXPECT_CALL(*primaryDispSync, computeNextRefresh(0, _)).WillRepeatedly(Return(0));
     EXPECT_CALL(*primaryDispSync, getPeriod())
             .WillRepeatedly(Return(FakeHwcDisplayInjector::DEFAULT_REFRESH_RATE));
-    EXPECT_CALL(*primaryDispSync, expectedPresentTime()).WillRepeatedly(Return(0));
+    EXPECT_CALL(*primaryDispSync, expectedPresentTime(_)).WillRepeatedly(Return(0));
     mFlinger.setupScheduler(std::move(primaryDispSync),
                             std::make_unique<mock::EventControlThread>(), std::move(eventThread),
                             std::move(sfEventThread));
diff --git a/services/surfaceflinger/tests/unittests/RefreshRateStatsTest.cpp b/services/surfaceflinger/tests/unittests/RefreshRateStatsTest.cpp
index 038e6e6..229adb5 100644
--- a/services/surfaceflinger/tests/unittests/RefreshRateStatsTest.cpp
+++ b/services/surfaceflinger/tests/unittests/RefreshRateStatsTest.cpp
@@ -80,7 +80,7 @@
 
 std::shared_ptr<const HWC2::Display::Config> RefreshRateStatsTest::createConfig(
         HwcConfigIndexType configId, int32_t configGroup, int64_t vsyncPeriod) {
-    return HWC2::Display::Config::Builder(mDisplay, hwc2_config_t(configId.value()))
+    return HWC2::Display::Config::Builder(mDisplay, configId.value())
             .setVsyncPeriod(int32_t(vsyncPeriod))
             .setConfigGroup(configGroup)
             .build();
diff --git a/services/surfaceflinger/tests/unittests/SetFrameRateTest.cpp b/services/surfaceflinger/tests/unittests/SetFrameRateTest.cpp
index b069085..0d6c799 100644
--- a/services/surfaceflinger/tests/unittests/SetFrameRateTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SetFrameRateTest.cpp
@@ -178,10 +178,10 @@
 
     auto primaryDispSync = std::make_unique<mock::DispSync>();
 
-    EXPECT_CALL(*primaryDispSync, computeNextRefresh(0)).WillRepeatedly(Return(0));
+    EXPECT_CALL(*primaryDispSync, computeNextRefresh(0, _)).WillRepeatedly(Return(0));
     EXPECT_CALL(*primaryDispSync, getPeriod())
             .WillRepeatedly(Return(FakeHwcDisplayInjector::DEFAULT_REFRESH_RATE));
-    EXPECT_CALL(*primaryDispSync, expectedPresentTime()).WillRepeatedly(Return(0));
+    EXPECT_CALL(*primaryDispSync, expectedPresentTime(_)).WillRepeatedly(Return(0));
     mFlinger.setupScheduler(std::move(primaryDispSync),
                             std::make_unique<mock::EventControlThread>(), std::move(eventThread),
                             std::move(sfEventThread));
diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
index 6995ee0..f75cd36 100644
--- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
+++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
@@ -57,6 +57,8 @@
 
 } // namespace Hwc2
 
+namespace hal = android::hardware::graphics::composer::hal;
+
 namespace surfaceflinger::test {
 
 class Factory final : public surfaceflinger::Factory {
@@ -257,12 +259,12 @@
         layer->editCompositionState()->sidebandStream = sidebandStream;
     }
 
-    void setLayerCompositionType(sp<Layer> layer, HWC2::Composition type) {
+    void setLayerCompositionType(sp<Layer> layer, hal::Composition type) {
         auto outputLayer = layer->findOutputLayerForDisplay(mFlinger->getDefaultDisplayDevice());
         LOG_ALWAYS_FATAL_IF(!outputLayer);
         auto& state = outputLayer->editState();
         LOG_ALWAYS_FATAL_IF(!outputLayer->getState().hwc);
-        (*state.hwc).hwcCompositionType = static_cast<Hwc2::IComposerClient::Composition>(type);
+        (*state.hwc).hwcCompositionType = type;
     };
 
     void setLayerPotentialCursor(sp<Layer> layer, bool potentialCursor) {
@@ -298,8 +300,8 @@
         return mFlinger->handleTransactionLocked(transactionFlags);
     }
 
-    auto onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
-                           HWC2::Connection connection) {
+    auto onHotplugReceived(int32_t sequenceId, hal::HWDisplayId display,
+                           hal::Connection connection) {
         return mFlinger->onHotplugReceived(sequenceId, display, connection);
     }
 
@@ -319,7 +321,7 @@
         return mFlinger->setPowerModeInternal(display, mode);
     }
 
-    auto onMessageReceived(int32_t what) { return mFlinger->onMessageReceived(what); }
+    auto onMessageReceived(int32_t what) { return mFlinger->onMessageReceived(what, systemTime()); }
 
     auto captureScreenImplLocked(
             const RenderArea& renderArea, SurfaceFlinger::TraverseLayersFunction traverseLayers,
@@ -428,12 +430,12 @@
      */
     struct HWC2Display : public HWC2::impl::Display {
         HWC2Display(Hwc2::Composer& composer,
-                    const std::unordered_set<HWC2::Capability>& capabilities, hwc2_display_t id,
-                    HWC2::DisplayType type)
+                    const std::unordered_set<hal::Capability>& capabilities, hal::HWDisplayId id,
+                    hal::DisplayType type)
               : HWC2::impl::Display(composer, capabilities, id, type) {}
         ~HWC2Display() {
             // Prevents a call to disable vsyncs.
-            mType = HWC2::DisplayType::Invalid;
+            mType = hal::DisplayType::INVALID;
         }
 
         auto& mutableIsConnected() { return this->mIsConnected; }
@@ -443,20 +445,19 @@
 
     class FakeHwcDisplayInjector {
     public:
-        static constexpr hwc2_display_t DEFAULT_HWC_DISPLAY_ID = 1000;
+        static constexpr hal::HWDisplayId DEFAULT_HWC_DISPLAY_ID = 1000;
         static constexpr int32_t DEFAULT_WIDTH = 1920;
         static constexpr int32_t DEFAULT_HEIGHT = 1280;
         static constexpr int32_t DEFAULT_REFRESH_RATE = 16'666'666;
         static constexpr int32_t DEFAULT_CONFIG_GROUP = 7;
         static constexpr int32_t DEFAULT_DPI = 320;
-        static constexpr hwc2_config_t DEFAULT_ACTIVE_CONFIG = 0;
+        static constexpr hal::HWConfigId DEFAULT_ACTIVE_CONFIG = 0;
         static constexpr int32_t DEFAULT_POWER_MODE = 2;
 
-        FakeHwcDisplayInjector(DisplayId displayId, HWC2::DisplayType hwcDisplayType,
-                               bool isPrimary)
+        FakeHwcDisplayInjector(DisplayId displayId, hal::DisplayType hwcDisplayType, bool isPrimary)
               : mDisplayId(displayId), mHwcDisplayType(hwcDisplayType), mIsPrimary(isPrimary) {}
 
-        auto& setHwcDisplayId(hwc2_display_t displayId) {
+        auto& setHwcDisplayId(hal::HWDisplayId displayId) {
             mHwcDisplayId = displayId;
             return *this;
         }
@@ -486,12 +487,12 @@
             return *this;
         }
 
-        auto& setActiveConfig(hwc2_config_t config) {
+        auto& setActiveConfig(hal::HWConfigId config) {
             mActiveConfig = config;
             return *this;
         }
 
-        auto& setCapabilities(const std::unordered_set<HWC2::Capability>* capabilities) {
+        auto& setCapabilities(const std::unordered_set<hal::Capability>* capabilities) {
             mCapabilities = capabilities;
             return *this;
         }
@@ -502,7 +503,7 @@
         }
 
         void inject(TestableSurfaceFlinger* flinger, Hwc2::Composer* composer) {
-            static const std::unordered_set<HWC2::Capability> defaultCapabilities;
+            static const std::unordered_set<hal::Capability> defaultCapabilities;
             if (mCapabilities == nullptr) mCapabilities = &defaultCapabilities;
 
             // Caution - Make sure that any values passed by reference here do
@@ -521,11 +522,11 @@
             config.setConfigGroup(mConfigGroup);
             display->mutableConfigs().emplace(static_cast<int32_t>(mActiveConfig), config.build());
             display->mutableIsConnected() = true;
-            display->setPowerMode(static_cast<HWC2::PowerMode>(mPowerMode));
+            display->setPowerMode(static_cast<hal::PowerMode>(mPowerMode));
 
             flinger->mutableHwcDisplayData()[mDisplayId].hwcDisplay = std::move(display);
 
-            if (mHwcDisplayType == HWC2::DisplayType::Physical) {
+            if (mHwcDisplayType == hal::DisplayType::PHYSICAL) {
                 flinger->mutableHwcPhysicalDisplayIdMap().emplace(mHwcDisplayId, mDisplayId);
                 (mIsPrimary ? flinger->mutableInternalHwcDisplayId()
                             : flinger->mutableExternalHwcDisplayId()) = mHwcDisplayId;
@@ -534,19 +535,19 @@
 
     private:
         const DisplayId mDisplayId;
-        const HWC2::DisplayType mHwcDisplayType;
+        const hal::DisplayType mHwcDisplayType;
         const bool mIsPrimary;
 
-        hwc2_display_t mHwcDisplayId = DEFAULT_HWC_DISPLAY_ID;
+        hal::HWDisplayId mHwcDisplayId = DEFAULT_HWC_DISPLAY_ID;
         int32_t mWidth = DEFAULT_WIDTH;
         int32_t mHeight = DEFAULT_HEIGHT;
         int32_t mRefreshRate = DEFAULT_REFRESH_RATE;
         int32_t mDpiX = DEFAULT_DPI;
         int32_t mConfigGroup = DEFAULT_CONFIG_GROUP;
         int32_t mDpiY = DEFAULT_DPI;
-        hwc2_config_t mActiveConfig = DEFAULT_ACTIVE_CONFIG;
+        hal::HWConfigId mActiveConfig = DEFAULT_ACTIVE_CONFIG;
         int32_t mPowerMode = DEFAULT_POWER_MODE;
-        const std::unordered_set<HWC2::Capability>* mCapabilities = nullptr;
+        const std::unordered_set<hal::Capability>* mCapabilities = nullptr;
     };
 
     class FakeDisplayDeviceInjector {
@@ -554,7 +555,7 @@
         FakeDisplayDeviceInjector(TestableSurfaceFlinger& flinger,
                                   std::shared_ptr<compositionengine::Display> compositionDisplay,
                                   std::optional<DisplayConnectionType> connectionType,
-                                  std::optional<hwc2_display_t> hwcDisplayId, bool isPrimary)
+                                  std::optional<hal::HWDisplayId> hwcDisplayId, bool isPrimary)
               : mFlinger(flinger),
                 mCreationArgs(flinger.mFlinger.get(), mDisplayToken, compositionDisplay),
                 mHwcDisplayId(hwcDisplayId) {
@@ -647,7 +648,7 @@
         TestableSurfaceFlinger& mFlinger;
         sp<BBinder> mDisplayToken = new BBinder();
         DisplayDeviceCreationArgs mCreationArgs;
-        const std::optional<hwc2_display_t> mHwcDisplayId;
+        const std::optional<hal::HWDisplayId> mHwcDisplayId;
     };
 
     surfaceflinger::test::Factory mFactory;
diff --git a/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp b/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp
index 1f04673..5de6bac 100644
--- a/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp
+++ b/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp
@@ -377,6 +377,21 @@
     EXPECT_THAT(result, HasSubstr(expectedResult));
 }
 
+TEST_F(TimeStatsTest, canIncreaseCompositionStrategyChanges) {
+    // this stat is not in the proto so verify by checking the string dump
+    constexpr size_t COMPOSITION_STRATEGY_CHANGES = 2;
+
+    EXPECT_TRUE(inputCommand(InputCommand::ENABLE, FMT_STRING).empty());
+    for (size_t i = 0; i < COMPOSITION_STRATEGY_CHANGES; i++) {
+        ASSERT_NO_FATAL_FAILURE(mTimeStats->incrementCompositionStrategyChanges());
+    }
+
+    const std::string result(inputCommand(InputCommand::DUMP_ALL, FMT_STRING));
+    const std::string expectedResult =
+            "compositionStrategyChanges = " + std::to_string(COMPOSITION_STRATEGY_CHANGES);
+    EXPECT_THAT(result, HasSubstr(expectedResult));
+}
+
 TEST_F(TimeStatsTest, canAverageFrameDuration) {
     EXPECT_TRUE(inputCommand(InputCommand::ENABLE, FMT_STRING).empty());
     mTimeStats->setPowerMode(HWC_POWER_MODE_NORMAL);
@@ -760,6 +775,7 @@
     EXPECT_TRUE(inputCommand(InputCommand::ENABLE, FMT_STRING).empty());
     ASSERT_NO_FATAL_FAILURE(mTimeStats->incrementClientCompositionReusedFrames());
     ASSERT_NO_FATAL_FAILURE(mTimeStats->incrementRefreshRateSwitches());
+    ASSERT_NO_FATAL_FAILURE(mTimeStats->incrementCompositionStrategyChanges());
     mTimeStats->setPowerMode(HWC_POWER_MODE_NORMAL);
     mTimeStats
             ->recordFrameDuration(std::chrono::duration_cast<std::chrono::nanoseconds>(1ms).count(),
@@ -776,6 +792,7 @@
     const std::string result(inputCommand(InputCommand::DUMP_ALL, FMT_STRING));
     EXPECT_THAT(result, HasSubstr("clientCompositionReusedFrames = 0"));
     EXPECT_THAT(result, HasSubstr("refreshRateSwitches = 0"));
+    EXPECT_THAT(result, HasSubstr("compositionStrategyChanges = 0"));
     EXPECT_THAT(result, HasSubstr("averageFrameDuration = 0.000 ms"));
     EXPECT_THAT(result, HasSubstr("averageRenderEngineTiming = 0.000 ms"));
 }
diff --git a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp
index f1739e5..fbbb69c 100644
--- a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp
+++ b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp
@@ -76,7 +76,7 @@
                         new EventThreadConnection(sfEventThread.get(), ResyncCallback(),
                                                   ISurfaceComposer::eConfigChangedSuppress)));
 
-        EXPECT_CALL(*mPrimaryDispSync, computeNextRefresh(0)).WillRepeatedly(Return(0));
+        EXPECT_CALL(*mPrimaryDispSync, computeNextRefresh(0, _)).WillRepeatedly(Return(0));
         EXPECT_CALL(*mPrimaryDispSync, getPeriod())
                 .WillRepeatedly(Return(FakeHwcDisplayInjector::DEFAULT_REFRESH_RATE));
 
@@ -126,7 +126,7 @@
         ASSERT_EQ(0, mFlinger.getTransactionQueue().size());
         // called in SurfaceFlinger::signalTransaction
         EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
-        EXPECT_CALL(*mPrimaryDispSync, expectedPresentTime()).WillOnce(Return(systemTime()));
+        EXPECT_CALL(*mPrimaryDispSync, expectedPresentTime(_)).WillOnce(Return(systemTime()));
         TransactionInfo transaction;
         setupSingle(transaction, flags, syncInputWindows,
                     /*desiredPresentTime*/ -1);
@@ -159,7 +159,7 @@
         // first check will see desired present time has not passed,
         // but afterwards it will look like the desired present time has passed
         nsecs_t time = systemTime();
-        EXPECT_CALL(*mPrimaryDispSync, expectedPresentTime())
+        EXPECT_CALL(*mPrimaryDispSync, expectedPresentTime(_))
                 .WillOnce(Return(time + nsecs_t(5 * 1e8)));
         TransactionInfo transaction;
         setupSingle(transaction, flags, syncInputWindows,
@@ -182,7 +182,7 @@
         // called in SurfaceFlinger::signalTransaction
         nsecs_t time = systemTime();
         EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
-        EXPECT_CALL(*mPrimaryDispSync, expectedPresentTime())
+        EXPECT_CALL(*mPrimaryDispSync, expectedPresentTime(_))
                 .WillOnce(Return(time + nsecs_t(5 * 1e8)));
         // transaction that should go on the pending thread
         TransactionInfo transactionA;
@@ -247,7 +247,7 @@
     EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
 
     // nsecs_t time = systemTime();
-    EXPECT_CALL(*mPrimaryDispSync, expectedPresentTime())
+    EXPECT_CALL(*mPrimaryDispSync, expectedPresentTime(_))
             .WillOnce(Return(nsecs_t(5 * 1e8)))
             .WillOnce(Return(s2ns(2)));
     TransactionInfo transactionA; // transaction to go on pending queue
diff --git a/services/surfaceflinger/tests/unittests/VSyncReactorTest.cpp b/services/surfaceflinger/tests/unittests/VSyncReactorTest.cpp
index 4f150ef..32c9045 100644
--- a/services/surfaceflinger/tests/unittests/VSyncReactorTest.cpp
+++ b/services/surfaceflinger/tests/unittests/VSyncReactorTest.cpp
@@ -270,7 +270,7 @@
             .Times(1)
             .WillOnce(Return(fakeTimestamp));
 
-    EXPECT_THAT(mReactor.computeNextRefresh(0), Eq(fakeTimestamp));
+    EXPECT_THAT(mReactor.computeNextRefresh(0, mMockClock->now()), Eq(fakeTimestamp));
 }
 
 TEST_F(VSyncReactorTest, queriesTrackerForExpectedPresentTime) {
@@ -280,7 +280,7 @@
             .Times(1)
             .WillOnce(Return(fakeTimestamp));
 
-    EXPECT_THAT(mReactor.expectedPresentTime(), Eq(fakeTimestamp));
+    EXPECT_THAT(mReactor.expectedPresentTime(mMockClock->now()), Eq(fakeTimestamp));
 }
 
 TEST_F(VSyncReactorTest, queriesTrackerForNextRefreshFuture) {
@@ -292,7 +292,7 @@
     EXPECT_CALL(*mMockTracker, currentPeriod()).WillOnce(Return(fakePeriod));
     EXPECT_CALL(*mMockTracker, nextAnticipatedVSyncTimeFrom(mFakeNow + numPeriodsOut * fakePeriod))
             .WillOnce(Return(fakeTimestamp));
-    EXPECT_THAT(mReactor.computeNextRefresh(numPeriodsOut), Eq(fakeTimestamp));
+    EXPECT_THAT(mReactor.computeNextRefresh(numPeriodsOut, mMockClock->now()), Eq(fakeTimestamp));
 }
 
 TEST_F(VSyncReactorTest, getPeriod) {
diff --git a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplay.h b/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplay.h
index 3968035..67d3e1c 100644
--- a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplay.h
+++ b/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplay.h
@@ -20,78 +20,80 @@
 
 #include "DisplayHardware/HWC2.h"
 
-using HWC2::Error;
-using HWC2::Layer;
+using android::HWC2::Layer;
 
 namespace android {
 namespace Hwc2 {
 namespace mock {
 
+namespace hal = android::hardware::graphics::composer::hal;
+
 class Display : public HWC2::Display {
 public:
-    using Error = ::Error;
     using Layer = ::Layer;
 
     Display();
     ~Display();
 
-    MOCK_CONST_METHOD0(getId, hwc2_layer_t());
+    MOCK_CONST_METHOD0(getId, hal::HWDisplayId());
     MOCK_CONST_METHOD0(isConnected, bool());
     MOCK_METHOD1(setConnected, void(bool));
-    MOCK_CONST_METHOD0(getCapabilities, const std::unordered_set<HWC2::DisplayCapability>&());
+    MOCK_CONST_METHOD0(getCapabilities, const std::unordered_set<hal::DisplayCapability>&());
 
-    MOCK_METHOD0(acceptChanges, Error());
-    MOCK_METHOD1(createLayer, Error(Layer**));
-    MOCK_METHOD1(destroyLayer, Error(Layer*));
-    MOCK_CONST_METHOD1(getActiveConfig, Error(std::shared_ptr<const Config>*));
-    MOCK_CONST_METHOD1(getActiveConfigIndex, Error(int* outIndex));
-    MOCK_METHOD1(getChangedCompositionTypes, Error(std::unordered_map<Layer*, HWC2::Composition>*));
-    MOCK_CONST_METHOD1(getColorModes, Error(std::vector<android::ui::ColorMode>*));
+    MOCK_METHOD0(acceptChanges, hal::Error());
+    MOCK_METHOD1(createLayer, hal::Error(Layer**));
+    MOCK_METHOD1(destroyLayer, hal::Error(Layer*));
+    MOCK_CONST_METHOD1(getActiveConfig, hal::Error(std::shared_ptr<const Config>*));
+    MOCK_CONST_METHOD1(getActiveConfigIndex, hal::Error(int* outIndex));
+    MOCK_METHOD1(getChangedCompositionTypes,
+                 hal::Error(std::unordered_map<Layer*, hal::Composition>*));
+    MOCK_CONST_METHOD1(getColorModes, hal::Error(std::vector<hal::ColorMode>*));
 
     MOCK_CONST_METHOD0(getSupportedPerFrameMetadata, int32_t());
     MOCK_CONST_METHOD2(getRenderIntents,
-                       Error(android::ui::ColorMode, std::vector<android::ui::RenderIntent>*));
-    MOCK_METHOD2(getDataspaceSaturationMatrix, Error(android::ui::Dataspace, android::mat4*));
+                       hal::Error(hal::ColorMode, std::vector<hal::RenderIntent>*));
+    MOCK_METHOD2(getDataspaceSaturationMatrix, hal::Error(hal::Dataspace, android::mat4*));
     MOCK_CONST_METHOD0(getConfigs, std::vector<std::shared_ptr<const Config>>());
 
-    MOCK_CONST_METHOD1(getName, Error(std::string*));
+    MOCK_CONST_METHOD1(getName, hal::Error(std::string*));
     MOCK_METHOD2(getRequests,
-                 Error(HWC2::DisplayRequest*, std::unordered_map<Layer*, HWC2::LayerRequest>*));
-    MOCK_CONST_METHOD1(getType, Error(HWC2::DisplayType*));
-    MOCK_CONST_METHOD1(supportsDoze, Error(bool*));
-    MOCK_CONST_METHOD1(getHdrCapabilities, Error(android::HdrCapabilities*));
+                 hal::Error(hal::DisplayRequest*, std::unordered_map<Layer*, hal::LayerRequest>*));
+    MOCK_CONST_METHOD1(getType, hal::Error(hal::DisplayType*));
+    MOCK_CONST_METHOD1(supportsDoze, hal::Error(bool*));
+    MOCK_CONST_METHOD1(getHdrCapabilities, hal::Error(android::HdrCapabilities*));
     MOCK_CONST_METHOD3(getDisplayedContentSamplingAttributes,
-                       Error(android::ui::PixelFormat*, android::ui::Dataspace*, uint8_t*));
-    MOCK_CONST_METHOD3(setDisplayContentSamplingEnabled, Error(bool, uint8_t, uint64_t));
+                       hal::Error(hal::PixelFormat*, hal::Dataspace*, uint8_t*));
+    MOCK_CONST_METHOD3(setDisplayContentSamplingEnabled, hal::Error(bool, uint8_t, uint64_t));
     MOCK_CONST_METHOD3(getDisplayedContentSample,
-                       Error(uint64_t, uint64_t, android::DisplayedFrameStats*));
-    MOCK_CONST_METHOD1(getReleaseFences,
-                       Error(std::unordered_map<Layer*, android::sp<android::Fence>>* outFences));
-    MOCK_METHOD1(present, Error(android::sp<android::Fence>*));
-    MOCK_METHOD1(setActiveConfig, Error(const std::shared_ptr<const HWC2::Display::Config>&));
+                       hal::Error(uint64_t, uint64_t, android::DisplayedFrameStats*));
+    MOCK_CONST_METHOD1(
+            getReleaseFences,
+            hal::Error(std::unordered_map<Layer*, android::sp<android::Fence>>* outFences));
+    MOCK_METHOD1(present, hal::Error(android::sp<android::Fence>*));
+    MOCK_METHOD1(setActiveConfig, hal::Error(const std::shared_ptr<const HWC2::Display::Config>&));
     MOCK_METHOD4(setClientTarget,
-                 Error(uint32_t, const android::sp<android::GraphicBuffer>&,
-                       const android::sp<android::Fence>&, android::ui::Dataspace));
-    MOCK_METHOD2(setColorMode, Error(android::ui::ColorMode, android::ui::RenderIntent));
-    MOCK_METHOD2(setColorTransform, Error(const android::mat4&, android_color_transform_t));
+                 hal::Error(uint32_t, const android::sp<android::GraphicBuffer>&,
+                            const android::sp<android::Fence>&, hal::Dataspace));
+    MOCK_METHOD2(setColorMode, hal::Error(hal::ColorMode, hal::RenderIntent));
+    MOCK_METHOD2(setColorTransform, hal::Error(const android::mat4&, hal::ColorTransform));
     MOCK_METHOD2(setOutputBuffer,
-                 Error(const android::sp<android::GraphicBuffer>&,
-                       const android::sp<android::Fence>&));
-    MOCK_METHOD1(setPowerMode, Error(HWC2::PowerMode));
-    MOCK_METHOD1(setVsyncEnabled, Error(HWC2::Vsync));
-    MOCK_METHOD2(validate, Error(uint32_t*, uint32_t*));
+                 hal::Error(const android::sp<android::GraphicBuffer>&,
+                            const android::sp<android::Fence>&));
+    MOCK_METHOD1(setPowerMode, hal::Error(hal::PowerMode));
+    MOCK_METHOD1(setVsyncEnabled, hal::Error(hal::Vsync));
+    MOCK_METHOD2(validate, hal::Error(uint32_t*, uint32_t*));
     MOCK_METHOD4(presentOrValidate,
-                 Error(uint32_t*, uint32_t*, android::sp<android::Fence>*, uint32_t*));
-    MOCK_CONST_METHOD1(setDisplayBrightness, Error(float));
-    MOCK_CONST_METHOD1(getDisplayVsyncPeriod, Error(nsecs_t*));
+                 hal::Error(uint32_t*, uint32_t*, android::sp<android::Fence>*, uint32_t*));
+    MOCK_CONST_METHOD1(setDisplayBrightness, hal::Error(float));
+    MOCK_CONST_METHOD1(getDisplayVsyncPeriod, hal::Error(nsecs_t*));
     MOCK_METHOD3(setActiveConfigWithConstraints,
-                 Error(const std::shared_ptr<const HWC2::Display::Config>&,
-                       const HWC2::VsyncPeriodChangeConstraints&,
-                       HWC2::VsyncPeriodChangeTimeline*));
-    MOCK_CONST_METHOD1(setAutoLowLatencyMode, Error(bool on));
-    MOCK_CONST_METHOD1(getSupportedContentTypes, Error(std::vector<HWC2::ContentType>*));
-    MOCK_CONST_METHOD1(setContentType, Error(HWC2::ContentType));
-    MOCK_CONST_METHOD1(getConnectionType, Error(android::DisplayConnectionType*));
+                 hal::Error(const std::shared_ptr<const HWC2::Display::Config>&,
+                            const hal::VsyncPeriodChangeConstraints&,
+                            hal::VsyncPeriodChangeTimeline*));
+    MOCK_CONST_METHOD1(setAutoLowLatencyMode, hal::Error(bool on));
+    MOCK_CONST_METHOD1(getSupportedContentTypes, hal::Error(std::vector<hal::ContentType>*));
+    MOCK_CONST_METHOD1(setContentType, hal::Error(hal::ContentType));
+    MOCK_CONST_METHOD1(getConnectionType, hal::Error(android::DisplayConnectionType*));
     MOCK_CONST_METHOD0(isVsyncPeriodSwitchSupported, bool());
 };
 
diff --git a/services/surfaceflinger/tests/unittests/mock/MockDispSync.h b/services/surfaceflinger/tests/unittests/mock/MockDispSync.h
index a2ae6c9..b39487c 100644
--- a/services/surfaceflinger/tests/unittests/mock/MockDispSync.h
+++ b/services/surfaceflinger/tests/unittests/mock/MockDispSync.h
@@ -37,9 +37,9 @@
     MOCK_METHOD0(getPeriod, nsecs_t());
     MOCK_METHOD0(getIntendedPeriod, nsecs_t());
     MOCK_METHOD1(setRefreshSkipCount, void(int));
-    MOCK_CONST_METHOD1(computeNextRefresh, nsecs_t(int));
+    MOCK_CONST_METHOD2(computeNextRefresh, nsecs_t(int, nsecs_t));
     MOCK_METHOD1(setIgnorePresentFences, void(bool));
-    MOCK_METHOD0(expectedPresentTime, nsecs_t());
+    MOCK_METHOD1(expectedPresentTime, nsecs_t(nsecs_t));
 
     MOCK_CONST_METHOD1(dump, void(std::string&));
 
diff --git a/services/surfaceflinger/tests/unittests/mock/MockTimeStats.h b/services/surfaceflinger/tests/unittests/mock/MockTimeStats.h
index 9ea4dd0..dca1070 100644
--- a/services/surfaceflinger/tests/unittests/mock/MockTimeStats.h
+++ b/services/surfaceflinger/tests/unittests/mock/MockTimeStats.h
@@ -37,6 +37,7 @@
     MOCK_METHOD0(incrementClientCompositionFrames, void());
     MOCK_METHOD0(incrementClientCompositionReusedFrames, void());
     MOCK_METHOD0(incrementRefreshRateSwitches, void());
+    MOCK_METHOD0(incrementCompositionStrategyChanges, void());
     MOCK_METHOD1(recordDisplayEventConnectionCount, void(int32_t));
     MOCK_METHOD2(recordFrameDuration, void(nsecs_t, nsecs_t));
     MOCK_METHOD2(recordRenderEngineDuration, void(nsecs_t, nsecs_t));
diff --git a/services/surfaceflinger/tests/utils/TransactionUtils.h b/services/surfaceflinger/tests/utils/TransactionUtils.h
index 2c63da0..8e1f943 100644
--- a/services/surfaceflinger/tests/utils/TransactionUtils.h
+++ b/services/surfaceflinger/tests/utils/TransactionUtils.h
@@ -17,18 +17,13 @@
 #pragma once
 
 #include <chrono>
-#include <gtest/gtest.h>
 
 #include <android/native_window.h>
-#include <hardware/hwcomposer_defs.h>
-
 #include <binder/IPCThreadState.h>
-
+#include <gtest/gtest.h>
 #include <gui/Surface.h>
 #include <gui/SurfaceComposerClient.h>
-
 #include <private/gui/ComposerService.h>
-
 #include <ui/GraphicBuffer.h>
 #include <ui/Rect.h>