Merge "Clean up and fix skia-RenderEngine tests"
diff --git a/cmds/dumpstate/DumpstateService.cpp b/cmds/dumpstate/DumpstateService.cpp
index bfcc058..ba25a5a 100644
--- a/cmds/dumpstate/DumpstateService.cpp
+++ b/cmds/dumpstate/DumpstateService.cpp
@@ -39,8 +39,13 @@
     std::string calling_package;
 };
 
-static binder::Status exception(uint32_t code, const std::string& msg) {
-    MYLOGE("%s (%d) ", msg.c_str(), code);
+static binder::Status exception(uint32_t code, const std::string& msg,
+                                const std::string& extra_msg = "") {
+    if (extra_msg.empty()) {
+        MYLOGE("%s (%d) ", msg.c_str(), code);
+    } else {
+        MYLOGE("%s %s (%d) ", msg.c_str(), extra_msg.c_str(), code);
+    }
     return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
 }
 
@@ -60,7 +65,7 @@
 
 }  // namespace
 
-DumpstateService::DumpstateService() : ds_(nullptr) {
+DumpstateService::DumpstateService() : ds_(nullptr), calling_uid_(-1), calling_package_() {
 }
 
 char const* DumpstateService::getServiceName() {
@@ -131,6 +136,10 @@
     ds_->SetOptions(std::move(options));
     ds_->listener_ = listener;
 
+    // Track caller info for cancellation purposes.
+    calling_uid_ = calling_uid;
+    calling_package_ = calling_package;
+
     DumpstateInfo* ds_info = new DumpstateInfo();
     ds_info->ds = ds_;
     ds_info->calling_uid = calling_uid;
@@ -149,8 +158,20 @@
     return binder::Status::ok();
 }
 
-binder::Status DumpstateService::cancelBugreport() {
+binder::Status DumpstateService::cancelBugreport(int32_t calling_uid,
+                                                 const std::string& calling_package) {
     std::lock_guard<std::mutex> lock(lock_);
+    if (calling_uid != calling_uid_ || calling_package != calling_package_) {
+        // Note: we use a SecurityException to prevent BugreportManagerServiceImpl from killing the
+        // report in progress (from another caller).
+        return exception(
+            binder::Status::EX_SECURITY,
+            StringPrintf("Cancellation requested by %d/%s does not match report in "
+                         "progress",
+                         calling_uid, calling_package.c_str()),
+            // Sharing the owner of the BR is a (minor) leak, so leave it out of the app's exception
+            StringPrintf("started by %d/%s", calling_uid_, calling_package_.c_str()));
+    }
     ds_->Cancel();
     return binder::Status::ok();
 }
diff --git a/cmds/dumpstate/DumpstateService.h b/cmds/dumpstate/DumpstateService.h
index ac8d3ac..3ec8471 100644
--- a/cmds/dumpstate/DumpstateService.h
+++ b/cmds/dumpstate/DumpstateService.h
@@ -44,8 +44,7 @@
                                   const sp<IDumpstateListener>& listener,
                                   bool is_screenshot_requested) override;
 
-    // No-op
-    binder::Status cancelBugreport();
+    binder::Status cancelBugreport(int32_t calling_uid, const std::string& calling_package);
 
   private:
     // Dumpstate object which contains all the bugreporting logic.
@@ -53,6 +52,8 @@
     // one bugreport.
     // This service does not own this object.
     Dumpstate* ds_;
+    int32_t calling_uid_;
+    std::string calling_package_;
     std::mutex lock_;
 };
 
diff --git a/cmds/dumpstate/DumpstateUtil.cpp b/cmds/dumpstate/DumpstateUtil.cpp
index eeaa5a3..c833d0e 100644
--- a/cmds/dumpstate/DumpstateUtil.cpp
+++ b/cmds/dumpstate/DumpstateUtil.cpp
@@ -124,6 +124,12 @@
     return *this;
 }
 
+CommandOptions::CommandOptionsBuilder&
+CommandOptions::CommandOptionsBuilder::CloseAllFileDescriptorsOnExec() {
+    values.close_all_fds_on_exec_ = true;
+    return *this;
+}
+
 CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
     const std::string& message) {
     values.logging_message_ = message;
@@ -137,6 +143,7 @@
 CommandOptions::CommandOptionsValues::CommandOptionsValues(int64_t timeout_ms)
     : timeout_ms_(timeout_ms),
       always_(false),
+      close_all_fds_on_exec_(false),
       account_mode_(DONT_DROP_ROOT),
       output_mode_(NORMAL_OUTPUT),
       logging_message_("") {
@@ -157,6 +164,10 @@
     return values.always_;
 }
 
+bool CommandOptions::ShouldCloseAllFileDescriptorsOnExec() const {
+    return values.close_all_fds_on_exec_;
+}
+
 PrivilegeMode CommandOptions::PrivilegeMode() const {
     return values.account_mode_;
 }
@@ -277,7 +288,8 @@
         MYLOGI(logging_message.c_str(), command_string.c_str());
     }
 
-    bool silent = (options.OutputMode() == REDIRECT_TO_STDERR);
+    bool silent = (options.OutputMode() == REDIRECT_TO_STDERR ||
+                   options.ShouldCloseAllFileDescriptorsOnExec());
     bool redirecting_to_fd = STDOUT_FILENO != fd;
 
     if (PropertiesHelper::IsDryRun() && !options.Always()) {
@@ -314,7 +326,27 @@
             return -1;
         }
 
-        if (silent) {
+        if (options.ShouldCloseAllFileDescriptorsOnExec()) {
+            int devnull_fd = TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
+            TEMP_FAILURE_RETRY(dup2(devnull_fd, STDIN_FILENO));
+            close(devnull_fd);
+            devnull_fd = TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY));
+            TEMP_FAILURE_RETRY(dup2(devnull_fd, STDOUT_FILENO));
+            TEMP_FAILURE_RETRY(dup2(devnull_fd, STDERR_FILENO));
+            close(devnull_fd);
+            // This is to avoid leaking FDs that, accidentally, have not been
+            // marked as O_CLOEXEC. Leaking FDs across exec can cause failures
+            // when execing a process that has a SELinux auto_trans rule.
+            // Here we assume that the dumpstate process didn't open more than
+            // 1000 FDs. In theory we could iterate through /proc/self/fd/, but
+            // doing that in a fork-safe way is too complex and not worth it
+            // (opendir()/readdir() do heap allocations and take locks).
+            for (int i = 0; i < 1000; i++) {
+                if (i != STDIN_FILENO && i!= STDOUT_FILENO && i != STDERR_FILENO) {
+                    close(i);
+                }
+            }
+        } else if (silent) {
             // Redirects stdout to stderr
             TEMP_FAILURE_RETRY(dup2(STDERR_FILENO, STDOUT_FILENO));
         } else if (redirecting_to_fd) {
diff --git a/cmds/dumpstate/DumpstateUtil.h b/cmds/dumpstate/DumpstateUtil.h
index b099443..b00c46e 100644
--- a/cmds/dumpstate/DumpstateUtil.h
+++ b/cmds/dumpstate/DumpstateUtil.h
@@ -80,6 +80,7 @@
 
         int64_t timeout_ms_;
         bool always_;
+        bool close_all_fds_on_exec_;
         PrivilegeMode account_mode_;
         OutputMode output_mode_;
         std::string logging_message_;
@@ -112,6 +113,13 @@
         CommandOptionsBuilder& DropRoot();
         /* Sets the command's OutputMode as `REDIRECT_TO_STDERR` */
         CommandOptionsBuilder& RedirectStderr();
+        /* Closes all file descriptors before exec-ing the target process. This
+         * includes also stdio pipes, which are dup-ed on /dev/null. It prevents
+         * leaking opened FDs to the target process, which in turn can hit
+         * selinux denials in presence of auto_trans rules.
+         */
+        CommandOptionsBuilder& CloseAllFileDescriptorsOnExec();
+
         /* When not empty, logs a message before executing the command.
          * Must contain a `%s`, which will be replaced by the full command line, and end on `\n`. */
         CommandOptionsBuilder& Log(const std::string& message);
@@ -130,6 +138,8 @@
     int64_t TimeoutInMs() const;
     /* Checks whether the command should always be run, even on dry-run mode. */
     bool Always() const;
+    /* Checks whether all FDs should be closed prior to the exec() calls. */
+    bool ShouldCloseAllFileDescriptorsOnExec() const;
     /** Gets the PrivilegeMode of the command. */
     PrivilegeMode PrivilegeMode() const;
     /** Gets the OutputMode of the command. */
diff --git a/cmds/dumpstate/binder/android/os/IDumpstate.aidl b/cmds/dumpstate/binder/android/os/IDumpstate.aidl
index ba008bb..0793f0b 100644
--- a/cmds/dumpstate/binder/android/os/IDumpstate.aidl
+++ b/cmds/dumpstate/binder/android/os/IDumpstate.aidl
@@ -1,4 +1,4 @@
-/**
+/*
  * Copyright (c) 2016, The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -19,9 +19,9 @@
 import android.os.IDumpstateListener;
 
 /**
-  * Binder interface for the currently running dumpstate process.
-  * {@hide}
-  */
+ * Binder interface for the currently running dumpstate process.
+ * {@hide}
+ */
 interface IDumpstate {
 
     // NOTE: If you add to or change these modes, please also change the corresponding enums
@@ -49,10 +49,10 @@
     // Default mode.
     const int BUGREPORT_MODE_DEFAULT = 6;
 
-    /*
+    /**
      * Starts a bugreport in the background.
      *
-     *<p>Shows the user a dialog to get consent for sharing the bugreport with the calling
+     * <p>Shows the user a dialog to get consent for sharing the bugreport with the calling
      * application. If they deny {@link IDumpstateListener#onError} will be called. If they
      * consent and bugreport generation is successful artifacts will be copied to the given fds and
      * {@link IDumpstateListener#onFinished} will be called. If there
@@ -71,8 +71,15 @@
                         int bugreportMode, IDumpstateListener listener,
                         boolean isScreenshotRequested);
 
-    /*
+    /**
      * Cancels the bugreport currently in progress.
+     *
+     * <p>The caller must match the original caller of {@link #startBugreport} in order for the
+     * report to actually be cancelled. A {@link SecurityException} is reported if a mismatch is
+     * detected.
+     *
+     * @param callingUid UID of the original application that requested the cancellation.
+     * @param callingPackage package of the original application that requested the cancellation.
      */
-    void cancelBugreport();
+    void cancelBugreport(int callingUid, @utf8InCpp String callingPackage);
 }
diff --git a/cmds/dumpstate/dumpstate.cpp b/cmds/dumpstate/dumpstate.cpp
index c215c95..4a4a510 100644
--- a/cmds/dumpstate/dumpstate.cpp
+++ b/cmds/dumpstate/dumpstate.cpp
@@ -28,6 +28,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/mount.h>
 #include <sys/poll.h>
 #include <sys/prctl.h>
 #include <sys/resource.h>
@@ -174,6 +175,7 @@
 #define SNAPSHOTCTL_LOG_DIR "/data/misc/snapshotctl_log"
 #define LINKERCONFIG_DIR "/linkerconfig"
 #define PACKAGE_DEX_USE_LIST "/data/system/package-dex-usage.list"
+#define SYSTEM_TRACE_SNAPSHOT "/data/misc/perfetto-traces/bugreport/systrace.pftrace"
 
 // TODO(narayan): Since this information has to be kept in sync
 // with tombstoned, we should just put it in a common header.
@@ -1052,6 +1054,24 @@
     }
 }
 
+static void MaybeAddSystemTraceToZip() {
+    // This function copies into the .zip the system trace that was snapshotted
+    // by the early call to MaybeSnapshotSystemTrace(), if any background
+    // tracing was happening.
+    if (!ds.IsZipping()) {
+        MYLOGD("Not dumping system trace because it's not a zipped bugreport\n");
+        return;
+    }
+    if (!ds.has_system_trace_) {
+        // No background trace was happening at the time dumpstate was invoked.
+        return;
+    }
+    ds.AddZipEntry(
+            ZIP_ROOT_DIR + SYSTEM_TRACE_SNAPSHOT,
+            SYSTEM_TRACE_SNAPSHOT);
+    android::os::UnlinkAndLogOnError(SYSTEM_TRACE_SNAPSHOT);
+}
+
 static void DumpVisibleWindowViews() {
     if (!ds.IsZipping()) {
         MYLOGD("Not dumping visible views because it's not a zipped bugreport\n");
@@ -1549,7 +1569,7 @@
     dprintf(out_fd, "========================================================\n");
 
     RunDumpsys("APP PROVIDERS PLATFORM", {"activity", "provider", "all-platform"},
-            DUMPSYS_COMPONENTS_OPTIONS, out_fd);
+            DUMPSYS_COMPONENTS_OPTIONS, 0, out_fd);
 
     dprintf(out_fd, "========================================================\n");
     dprintf(out_fd, "== Running Application Providers (non-platform)\n");
@@ -1649,6 +1669,8 @@
 
     AddAnrTraceFiles();
 
+    MaybeAddSystemTraceToZip();
+
     // NOTE: tombstones are always added as separate entries in the zip archive
     // and are not interspersed with the main report.
     const bool tombstones_dumped = AddDumps(ds.tombstone_data_.begin(), ds.tombstone_data_.end(),
@@ -2157,6 +2179,22 @@
         return;
     }
 
+    /*
+     * mount debugfs for non-user builds which launch with S and unmount it
+     * after invoking dumpstateBoard_* methods. This is to enable debug builds
+     * to not have debugfs mounted during runtime. It will also ensure that
+     * debugfs is only accessed by the dumpstate HAL.
+     */
+    auto api_level = android::base::GetIntProperty("ro.product.first_api_level", 0);
+    bool mount_debugfs = !PropertiesHelper::IsUserBuild() && api_level >= 31;
+
+    if (mount_debugfs) {
+        RunCommand("mount debugfs", {"mount", "-t", "debugfs", "debugfs", "/sys/kernel/debug"},
+                   AS_ROOT_20);
+        RunCommand("chmod debugfs", {"chmod", "0755", "/sys/kernel/debug"},
+                   AS_ROOT_20);
+    }
+
     std::vector<std::string> paths;
     std::vector<android::base::ScopeGuard<std::function<void()>>> remover;
     for (int i = 0; i < NUM_OF_DUMPS; i++) {
@@ -2256,6 +2294,10 @@
                "there might be racing in content\n", killing_timeout_sec);
     }
 
+    if (mount_debugfs) {
+        RunCommand("unmount debugfs", {"umount", "/sys/kernel/debug"}, AS_ROOT_20);
+    }
+
     auto file_sizes = std::make_unique<ssize_t[]>(paths.size());
     for (size_t i = 0; i < paths.size(); i++) {
         struct stat s;
@@ -2866,6 +2908,13 @@
         RunDumpsysCritical();
     }
     MaybeTakeEarlyScreenshot();
+
+    if (!is_dumpstate_restricted) {
+        // Snapshot the system trace now (if running) to avoid that dumpstate's
+        // own activity pushes out interesting data from the trace ring buffer.
+        // The trace file is added to the zip by MaybeAddSystemTraceToZip().
+        MaybeSnapshotSystemTrace();
+    }
     onUiIntensiveBugreportDumpsFinished(calling_uid);
     MaybeCheckUserConsent(calling_uid, calling_package);
     if (options_->telephony_only) {
@@ -2956,6 +3005,26 @@
     TakeScreenshot();
 }
 
+void Dumpstate::MaybeSnapshotSystemTrace() {
+    // If a background system trace is happening and is marked as "suitable for
+    // bugreport" (i.e. bugreport_score > 0 in the trace config), this command
+    // will stop it and serialize into SYSTEM_TRACE_SNAPSHOT. In the (likely)
+    // case that no trace is ongoing, this command is a no-op.
+    // Note: this should not be enqueued as we need to freeze the trace before
+    // dumpstate starts. Otherwise the trace ring buffers will contain mostly
+    // the dumpstate's own activity which is irrelevant.
+    int res = RunCommand(
+        "SERIALIZE PERFETTO TRACE",
+        {"perfetto", "--save-for-bugreport"},
+        CommandOptions::WithTimeout(10)
+            .DropRoot()
+            .CloseAllFileDescriptorsOnExec()
+            .Build());
+    has_system_trace_ = res == 0;
+    // MaybeAddSystemTraceToZip() will take care of copying the trace in the zip
+    // file in the later stages.
+}
+
 void Dumpstate::onUiIntensiveBugreportDumpsFinished(int32_t calling_uid) {
     if (calling_uid == AID_SHELL || !CalledByApi()) {
         return;
diff --git a/cmds/dumpstate/dumpstate.h b/cmds/dumpstate/dumpstate.h
index 255243f..f83968b 100644
--- a/cmds/dumpstate/dumpstate.h
+++ b/cmds/dumpstate/dumpstate.h
@@ -458,6 +458,11 @@
     // Whether it should take an screenshot earlier in the process.
     bool do_early_screenshot_ = false;
 
+    // This is set to true when the trace snapshot request in the early call to
+    // MaybeSnapshotSystemTrace(). When this is true, the later stages of
+    // dumpstate will append the trace to the zip archive.
+    bool has_system_trace_ = false;
+
     std::unique_ptr<Progress> progress_;
 
     // When set, defines a socket file-descriptor use to report progress to bugreportz
@@ -543,6 +548,7 @@
     RunStatus DumpstateDefaultAfterCritical();
 
     void MaybeTakeEarlyScreenshot();
+    void MaybeSnapshotSystemTrace();
 
     void onUiIntensiveBugreportDumpsFinished(int32_t calling_uid);
 
diff --git a/cmds/dumpstate/tests/dumpstate_smoke_test.cpp b/cmds/dumpstate/tests/dumpstate_smoke_test.cpp
index fe6a34a..0e366cb 100644
--- a/cmds/dumpstate/tests/dumpstate_smoke_test.cpp
+++ b/cmds/dumpstate/tests/dumpstate_smoke_test.cpp
@@ -319,6 +319,16 @@
  */
 class BugreportSectionTest : public Test {
   public:
+    ZipArchiveHandle handle;
+
+    void SetUp() {
+        ASSERT_EQ(OpenArchive(ZippedBugreportGenerationTest::getZipFilePath().c_str(), &handle), 0);
+    }
+
+    void TearDown() {
+        CloseArchive(handle);
+    }
+
     static void SetUpTestCase() {
         ParseSections(ZippedBugreportGenerationTest::getZipFilePath().c_str(),
                       ZippedBugreportGenerationTest::sections.get());
@@ -343,6 +353,19 @@
         }
         FAIL() << sectionName << " not found.";
     }
+
+    /**
+     * Whether or not the content of the section is injected by other commands.
+     */
+    bool IsContentInjectedByOthers(const std::string& line) {
+        // Command header such as `------ APP ACTIVITIES (/system/bin/dumpsys activity -v) ------`.
+        static const std::regex kCommandHeader = std::regex{"------ .+ \\(.+\\) ------"};
+        std::smatch match;
+        if (std::regex_match(line, match, kCommandHeader)) {
+          return true;
+        }
+        return false;
+    }
 };
 
 TEST_F(BugreportSectionTest, Atleast3CriticalDumpsysSectionsGenerated) {
@@ -400,6 +423,28 @@
     SectionExists("wifi", /* bytes= */ 100000);
 }
 
+TEST_F(BugreportSectionTest, NoInjectedContentByOtherCommand) {
+    // Extract the main entry to a temp file
+    TemporaryFile tmp_binary;
+    ASSERT_NE(-1, tmp_binary.fd);
+    ExtractBugreport(&handle, tmp_binary.fd);
+
+    // Read line by line and identify sections
+    std::ifstream ifs(tmp_binary.path, std::ifstream::in);
+    std::string line;
+    std::string current_section_name;
+    while (std::getline(ifs, line)) {
+        std::string section_name;
+        if (IsSectionStart(line, &section_name)) {
+            current_section_name = section_name;
+        } else if (IsSectionEnd(line)) {
+            current_section_name = "";
+        } else if (!current_section_name.empty()) {
+            EXPECT_FALSE(IsContentInjectedByOthers(line));
+        }
+    }
+}
+
 class DumpstateBinderTest : public Test {
   protected:
     void SetUp() override {
diff --git a/include/android/bitmap.h b/include/android/bitmap.h
index f195399..d7f25e1 100644
--- a/include/android/bitmap.h
+++ b/include/android/bitmap.h
@@ -28,8 +28,23 @@
 
 #include <stdbool.h>
 #include <stdint.h>
+#include <stddef.h>
 #include <jni.h>
 
+#ifndef __ANDROID__
+    // Value copied from 'bionic/libc/include/android/api-level.h' which is not available on
+    // non Android systems. It is set to 10000 which is same as __ANDROID_API_FUTURE__ value.
+    #ifndef __ANDROID_API__
+        #define __ANDROID_API__ 10000
+    #endif
+
+    // Value copied from 'bionic/libc/include/android/versioning.h' which is not available on
+    // non Android systems
+    #ifndef __INTRODUCED_IN
+        #define __INTRODUCED_IN(api_level)
+    #endif
+#endif
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -152,8 +167,6 @@
  */
 int AndroidBitmap_unlockPixels(JNIEnv* env, jobject jbitmap);
 
-#if __ANDROID_API__ >= 30
-
 // Note: these values match android.graphics.Bitmap#compressFormat.
 
 /**
@@ -203,6 +216,8 @@
                                                 const void* data,
                                                 size_t size) __INTRODUCED_IN(30);
 
+#if __ANDROID_API__ >= 30
+
 /**
  *  Compress |pixels| as described by |info|.
  *
diff --git a/include/android/imagedecoder.h b/include/android/imagedecoder.h
index b5f3b10..c7a8939 100644
--- a/include/android/imagedecoder.h
+++ b/include/android/imagedecoder.h
@@ -51,6 +51,20 @@
 #include <android/rect.h>
 #include <stdint.h>
 
+#ifndef __ANDROID__
+    // Value copied from 'bionic/libc/include/android/api-level.h' which is not available on
+    // non Android systems. It is set to 10000 which is same as __ANDROID_API_FUTURE__ value.
+    #ifndef __ANDROID_API__
+        #define __ANDROID_API__ 10000
+    #endif
+
+    // Value copied from 'bionic/libc/include/android/versioning.h' which is not available on
+    // non Android systems
+    #ifndef __INTRODUCED_IN
+        #define __INTRODUCED_IN(api_level)
+    #endif
+#endif
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -583,7 +597,7 @@
  * Available since API level 30.
  *
  * Starting in API level 31, it can be used to decode all of the frames of an
- * animated image (i.e. GIF, WebP, HEIF) using new APIs. Internally,
+ * animated image (i.e. GIF, WebP) using new APIs. Internally,
  * AImageDecoder keeps track of its "current frame" - that is, the frame that
  * will be decoded by a call to AImageDecoder_decodeImage. At creation time, the
  * current frame is always the first frame, and multiple calls to this method
@@ -601,11 +615,12 @@
  * to determine whether other frames are independent, or what frames they rely on.
  *
  * If the current frame is marked {@link ANDROID_IMAGE_DECODER_DISPOSE_OP_PREVIOUS},
- * AImageDecoder_decodeImage will cache the |pixels| buffer prior to decoding
+ * AImageDecoder_decodeImage will store the |pixels| buffer prior to decoding
  * (note: this only happens for the first in a string of consecutive
  * ANDROID_IMAGE_DECODER_DISPOSE_OP_PREVIOUS frames). After advancing to the
- * following frame, AImageDecoder_decodeImage will restore the cached buffer
- * prior to decoding that frame.
+ * following frame, AImageDecoder_decodeImage will restore that buffer prior to
+ * decoding that frame. This is the default behavior, but it can be disabled
+ * by passing false to {@link AImageDecoder_setInternallyHandleDisposePrevious}.
  *
  * Ignoring timing information, display, etc, a client wishing to decode all
  * frames of an animated image may conceptually use code like the following:
@@ -712,7 +727,7 @@
  * - {@link ANDROID_IMAGE_DECODER_BAD_PARAMETER}: The AImageDecoder
  *   is null.
  */
-int32_t AImageDecoder_getRepeatCount(AImageDecoder* _Nonnull decoder);
+int32_t AImageDecoder_getRepeatCount(AImageDecoder* _Nonnull decoder)
         __INTRODUCED_IN(31);
 
 /**
@@ -923,11 +938,12 @@
     // No disposal. The following frame will be drawn directly
     // on top of this one.
     ANDROID_IMAGE_DECODER_DISPOSE_OP_NONE = 1,
-    // The frame’s rectangle is cleared (by AImageDecoder) before
-    // decoding the next frame.
+    // The frame’s rectangle is cleared to transparent (by AImageDecoder)
+    // before decoding the next frame.
     ANDROID_IMAGE_DECODER_DISPOSE_OP_BACKGROUND = 2,
-    // The frame’s rectangle is reverted (by AImageDecoder) to the
-    // prior frame before decoding the next frame.
+    // The frame’s rectangle is reverted to the prior frame before decoding
+    // the next frame. This is handled by AImageDecoder, unless
+    // {@link AImageDecoder_setInternallyHandleDisposePrevious} is set to false.
     ANDROID_IMAGE_DECODER_DISPOSE_OP_PREVIOUS = 3,
 };
 
@@ -995,6 +1011,42 @@
         const AImageDecoderFrameInfo* _Nonnull info)
         __INTRODUCED_IN(31);
 
+/**
+ * Whether to have AImageDecoder store the frame prior to a
+ * frame marked {@link ANDROID_IMAGE_DECODER_DISPOSE_OP_PREVIOUS}.
+ *
+ * Introduced in API 31.
+ *
+ * The default is true. Many images will not have such a frame (it
+ * is not supported by WebP, and only some GIFs use it). But
+ * if frame i is ANDROID_IMAGE_DECODER_DISPOSE_OP_PREVIOUS, then i+1
+ * may depend on i-1. When this setting is true, AImageDecoder will
+ * defensively copy frame i-1 (i.e. the contents of |pixels| in
+ * {@link AImageDecoder_decodeImage}) into an internal buffer so that
+ * it can be used to decode i+1.
+ *
+ * AImageDecoder will only store a single frame, at the size specified
+ * by {@link AImageDecoder_setTargetSize} (or the original dimensions
+ * if that method has not been called), and will discard it when it is
+ * no longer necessary.
+ *
+ * A client that desires to manually store such frames may set this to
+ * false, so that AImageDecoder does not need to store this extra
+ * frame. Instead, when decoding the same
+ * ANDROID_IMAGE_DECODER_DISPOSE_OP_PREVIOUS frame i, AImageDecoder
+ * will decode directly into |pixels|, assuming the client stored i-1.
+ * When asked to decode frame i+1, AImageDecoder will now assume that
+ * the client provided i-1 in |pixels|.
+ *
+ * @param handleInternally Whether AImageDecoder will internally
+ *               handle ANDROID_IMAGE_DECODER_DISPOSE_OP_PREVIOUS
+ *               frames.
+ */
+void AImageDecoder_setInternallyHandleDisposePrevious(
+        AImageDecoder* _Nonnull decoder, bool handleInternally)
+        __INTRODUCED_IN(31);
+
+
 #endif // __ANDROID_API__ >= 31
 
 #ifdef __cplusplus
diff --git a/include/android/permission_manager.h b/include/android/permission_manager.h
index 7817126..2d5d060 100644
--- a/include/android/permission_manager.h
+++ b/include/android/permission_manager.h
@@ -64,8 +64,6 @@
     PERMISSION_MANAGER_STATUS_SERVICE_UNAVAILABLE = -2,
 };
 
-#if __ANDROID_API__ >= 31
-
 /**
  * Checks whether the package with the given pid/uid has been granted a permission.
  *
@@ -84,8 +82,6 @@
                                            uid_t uid,
                                            int32_t* outResult) __INTRODUCED_IN(31);
 
-#endif // __ANDROID_API__ >= 31
-
 __END_DECLS
 
 #endif  // ANDROID_PERMISSION_MANAGER_H
diff --git a/libs/binder/Android.bp b/libs/binder/Android.bp
index 5fb0c1b..9ea9732 100644
--- a/libs/binder/Android.bp
+++ b/libs/binder/Android.bp
@@ -179,15 +179,26 @@
         "--header-filter=^.*frameworks/native/libs/binder/.*.h$",
     ],
     tidy_checks_as_errors: [
-        "*",
+        // Explicitly list the checks that should not occur in this module.
+        "abseil-*",
+        "android-*",
+        "bugprone-*",
+        "cert-*",
+        "clang-analyzer-*",
         "-clang-analyzer-core.CallAndMessage",
         "-clang-analyzer-core.uninitialized.Assign",
         "-clang-analyzer-unix.Malloc",
         "-clang-analyzer-deadcode.DeadStores",
         "-clang-analyzer-optin.cplusplus.UninitializedObject",
+        "google-*",
+        "-google-readability-*",
+        "-google-runtime-references",
+        "misc-*",
         "-misc-no-recursion",
         "-misc-redundant-expression",
         "-misc-unused-using-decls",
+        "performance*",
+        "portability*",
     ],
 }
 
diff --git a/libs/binder/include/binder/IInterface.h b/libs/binder/include/binder/IInterface.h
index 988508e..e2a0f87 100644
--- a/libs/binder/include/binder/IInterface.h
+++ b/libs/binder/include/binder/IInterface.h
@@ -232,7 +232,6 @@
   "android.gui.IGraphicBufferConsumer",
   "android.gui.IRegionSamplingListener",
   "android.gui.ITransactionComposerListener",
-  "android.gui.IScreenCaptureListener",
   "android.gui.SensorEventConnection",
   "android.gui.SensorServer",
   "android.hardware.ICamera",
diff --git a/libs/binder/ndk/Android.bp b/libs/binder/ndk/Android.bp
index d7b6fce..82f3882 100644
--- a/libs/binder/ndk/Android.bp
+++ b/libs/binder/ndk/Android.bp
@@ -104,15 +104,28 @@
         "--header-filter=^.*frameworks/native/libs/binder/.*.h$",
     ],
     tidy_checks_as_errors: [
-        "*",
+        // Explicitly list the checks that should not occur in this module.
+        "abseil-*",
+        "android-*",
+        "bugprone-*",
+        "cert-*",
+        "clang-analyzer-*",
         "-clang-analyzer-core.CallAndMessage",
         "-clang-analyzer-core.uninitialized.Assign",
         "-clang-analyzer-unix.Malloc",
         "-clang-analyzer-deadcode.DeadStores",
         "-clang-analyzer-optin.cplusplus.UninitializedObject",
+        "google-*",
+        "-google-readability-*",
+        "-google-runtime-references",
+        "misc-*",
         "-misc-no-recursion",
+        "-misc-non-private-member-variables-in-classes",
         "-misc-redundant-expression",
+        "-misc-unused-parameters",
         "-misc-unused-using-decls",
+        "performance*",
+        "portability*",
     ],
 }
 
diff --git a/libs/binder/ndk/ibinder.cpp b/libs/binder/ndk/ibinder.cpp
index 350c658..454fbd0 100644
--- a/libs/binder/ndk/ibinder.cpp
+++ b/libs/binder/ndk/ibinder.cpp
@@ -301,6 +301,26 @@
     return binder.get();
 }
 
+AIBinder_Weak* AIBinder_Weak_clone(const AIBinder_Weak* weak) {
+    if (weak == nullptr) {
+        return nullptr;
+    }
+
+    return new AIBinder_Weak{weak->binder};
+}
+
+bool AIBinder_lt(const AIBinder* lhs, const AIBinder* rhs) {
+    if (lhs == nullptr || rhs == nullptr) return lhs < rhs;
+
+    return const_cast<AIBinder*>(lhs)->getBinder() < const_cast<AIBinder*>(rhs)->getBinder();
+}
+
+bool AIBinder_Weak_lt(const AIBinder_Weak* lhs, const AIBinder_Weak* rhs) {
+    if (lhs == nullptr || rhs == nullptr) return lhs < rhs;
+
+    return lhs->binder < rhs->binder;
+}
+
 AIBinder_Class::AIBinder_Class(const char* interfaceDescriptor, AIBinder_Class_onCreate onCreate,
                                AIBinder_Class_onDestroy onDestroy,
                                AIBinder_Class_onTransact onTransact)
diff --git a/libs/binder/ndk/include_cpp/android/binder_interface_utils.h b/libs/binder/ndk/include_cpp/android/binder_interface_utils.h
index a4f4441..a1102e2 100644
--- a/libs/binder/ndk/include_cpp/android/binder_interface_utils.h
+++ b/libs/binder/ndk/include_cpp/android/binder_interface_utils.h
@@ -83,7 +83,8 @@
     template <class T, class... Args>
     static std::shared_ptr<T> make(Args&&... args) {
         T* t = new T(std::forward<Args>(args)...);
-        return t->template ref<T>();
+        // warning: Potential leak of memory pointed to by 't' [clang-analyzer-unix.Malloc]
+        return t->template ref<T>();  // NOLINT(clang-analyzer-unix.Malloc)
     }
 
     static void operator delete(void* p) { std::free(p); }
diff --git a/libs/binder/ndk/include_ndk/android/binder_ibinder.h b/libs/binder/ndk/include_ndk/android/binder_ibinder.h
index 5e1ed46..0ca3a07 100644
--- a/libs/binder/ndk/include_ndk/android/binder_ibinder.h
+++ b/libs/binder/ndk/include_ndk/android/binder_ibinder.h
@@ -657,6 +657,68 @@
  */
 const char* AIBinder_Class_getDescriptor(const AIBinder_Class* clazz) __INTRODUCED_IN(31);
 
+/**
+ * Whether AIBinder is less than another.
+ *
+ * This provides a per-process-unique total ordering of binders determined by
+ * an underlying allocation address where a null AIBinder* is considered to be
+ * ordered before all other binders.
+ *
+ * AIBinder* pointers themselves actually also create a per-process-unique total
+ * ordering. However, this ordering is inconsistent with AIBinder_Weak_lt for
+ * remote binders.
+ *
+ * Available since API level 31.
+ *
+ * \param lhs comparison object
+ * \param rhs comparison object
+ *
+ * \return whether "lhs < rhs" is true
+ */
+bool AIBinder_lt(const AIBinder* lhs, const AIBinder* rhs);
+
+/**
+ * Clone an AIBinder_Weak. Useful because even if a weak binder promotes to a
+ * null value, after further binder transactions, it may no longer promote to a
+ * null value.
+ *
+ * Available since API level 31.
+ *
+ * \param weak Object to clone
+ *
+ * \return clone of the input parameter. This must be deleted with
+ * AIBinder_Weak_delete. Null if weak input parameter is also null.
+ */
+AIBinder_Weak* AIBinder_Weak_clone(const AIBinder_Weak* weak);
+
+/**
+ * Whether AIBinder_Weak is less than another.
+ *
+ * This provides a per-process-unique total ordering of binders which is exactly
+ * the same as AIBinder_lt. Similarly, a null AIBinder_Weak* is considered to be
+ * ordered before all other weak references.
+ *
+ * If you have many AIBinder_Weak* objects which are all references to distinct
+ * binder objects which happen to have the same underlying address (as ordered
+ * by AIBinder_lt), these AIBinder_Weak* objects will retain the same order with
+ * respect to all other AIBinder_Weak* pointers with different underlying
+ * addresses and are also guaranteed to have a per-process-unique ordering. That
+ * is, even though multiple AIBinder* instances may happen to be allocated at
+ * the same underlying address, this function will still correctly distinguish
+ * that these are weak pointers to different binder objects.
+ *
+ * Unlike AIBinder*, the AIBinder_Weak* addresses themselves have nothing to do
+ * with the underlying binder.
+ *
+ * Available since API level 31.
+ *
+ * \param lhs comparison object
+ * \param rhs comparison object
+ *
+ * \return whether "lhs < rhs" is true
+ */
+bool AIBinder_Weak_lt(const AIBinder_Weak* lhs, const AIBinder_Weak* rhs);
+
 #endif  //__ANDROID_API__ >= 31
 
 __END_DECLS
diff --git a/libs/binder/ndk/libbinder_ndk.map.txt b/libs/binder/ndk/libbinder_ndk.map.txt
index e233ffd..9a93bf3 100644
--- a/libs/binder/ndk/libbinder_ndk.map.txt
+++ b/libs/binder/ndk/libbinder_ndk.map.txt
@@ -122,6 +122,9 @@
     AServiceManager_waitForService; # apex llndk
 
     AIBinder_Class_getDescriptor;
+    AIBinder_Weak_clone;
+    AIBinder_Weak_lt;
+    AIBinder_lt;
     AParcel_appendFrom;
     AParcel_create;
     AParcel_getDataSize;
diff --git a/libs/binder/tests/fuzzers/Android.bp b/libs/binder/tests/fuzzers/Android.bp
index c465bed..5531296 100644
--- a/libs/binder/tests/fuzzers/Android.bp
+++ b/libs/binder/tests/fuzzers/Android.bp
@@ -69,3 +69,18 @@
     defaults: ["binder_fuzz_defaults"],
     srcs: ["TextOutputFuzz.cpp"],
 }
+
+cc_fuzz {
+    name: "binder_bufferedTextOutputFuzz",
+    include_dirs: [
+        "frameworks/native/libs/binder",
+    ],
+    defaults: ["binder_fuzz_defaults"],
+    srcs: ["BufferedTextOutputFuzz.cpp"],
+}
+
+cc_fuzz {
+    name: "binder_memoryDealerFuzz",
+    defaults: ["binder_fuzz_defaults"],
+    srcs: ["MemoryDealerFuzz.cpp"],
+}
diff --git a/libs/binder/tests/fuzzers/BufferedTextOutputFuzz.cpp b/libs/binder/tests/fuzzers/BufferedTextOutputFuzz.cpp
new file mode 100644
index 0000000..09cb216
--- /dev/null
+++ b/libs/binder/tests/fuzzers/BufferedTextOutputFuzz.cpp
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#include <commonFuzzHelpers.h>
+#include <fuzzer/FuzzedDataProvider.h>
+#include <string>
+#include <vector>
+#include "BufferedTextOutput.h"
+
+namespace android {
+
+class FuzzBufferedTextOutput : public BufferedTextOutput {
+public:
+    FuzzBufferedTextOutput(uint32_t flags) : BufferedTextOutput(flags) {}
+    virtual status_t writeLines(const struct iovec& buf, size_t) {
+        size_t len = buf.iov_len;
+        void* tmp_buf = malloc(len);
+
+        if (tmp_buf == NULL) {
+            return status_t();
+        }
+
+        // This will attempt to read data from iov_base to ensure valid params were passed.
+        memcpy(tmp_buf, buf.iov_base, len);
+        free(tmp_buf);
+        return status_t();
+    }
+};
+
+// Fuzzer entry point.
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    FuzzedDataProvider fdp(data, size);
+    uint32_t flags = fdp.ConsumeIntegral<uint32_t>();
+    size_t push_count = 0;
+    std::shared_ptr<BufferedTextOutput> bTextOutput(new FuzzBufferedTextOutput(flags));
+
+    while (fdp.remaining_bytes() > 0) {
+        fdp.PickValueInArray<std::function<void()>>({
+                [&]() -> void {
+                    bTextOutput->pushBundle();
+                    push_count++;
+                },
+                [&]() -> void {
+                    std::string txt = fdp.ConsumeRandomLengthString(fdp.remaining_bytes());
+                    size_t len = fdp.ConsumeIntegralInRange<size_t>(0, txt.length());
+                    bTextOutput->print(txt.c_str(), len);
+                },
+                [&]() -> void {
+                    if (push_count == 0) return;
+
+                    bTextOutput->popBundle();
+                    push_count--;
+                },
+        })();
+    }
+
+    return 0;
+}
+} // namespace android
diff --git a/libs/binder/tests/fuzzers/MemoryDealerFuzz.cpp b/libs/binder/tests/fuzzers/MemoryDealerFuzz.cpp
new file mode 100644
index 0000000..f9dda8c
--- /dev/null
+++ b/libs/binder/tests/fuzzers/MemoryDealerFuzz.cpp
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#include <binder/MemoryDealer.h>
+#include <commonFuzzHelpers.h>
+#include <fuzzer/FuzzedDataProvider.h>
+#include <string>
+#include <unordered_set>
+
+namespace android {
+
+static constexpr size_t kMaxBufferSize = 10000;
+static constexpr size_t kMaxDealerSize = 1024 * 512;
+static constexpr size_t kMaxAllocSize = 1024;
+
+// Fuzzer entry point.
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    if (size > kMaxBufferSize) {
+        return 0;
+    }
+
+    FuzzedDataProvider fdp(data, size);
+    size_t dSize = fdp.ConsumeIntegralInRange<size_t>(0, kMaxDealerSize);
+    std::string name = fdp.ConsumeRandomLengthString(fdp.remaining_bytes());
+    uint32_t flags = fdp.ConsumeIntegral<uint32_t>();
+    sp<MemoryDealer> dealer = new MemoryDealer(dSize, name.c_str(), flags);
+
+    // This is used to track offsets that have been freed already to avoid an expected fatal log.
+    std::unordered_set<size_t> free_list;
+
+    while (fdp.remaining_bytes() > 0) {
+        fdp.PickValueInArray<std::function<void()>>({
+                [&]() -> void { dealer->getAllocationAlignment(); },
+                [&]() -> void { dealer->getMemoryHeap(); },
+                [&]() -> void {
+                    size_t offset = fdp.ConsumeIntegral<size_t>();
+
+                    // Offset has already been freed, so return instead.
+                    if (free_list.find(offset) != free_list.end()) return;
+
+                    dealer->deallocate(offset);
+                    free_list.insert(offset);
+                },
+                [&]() -> void {
+                    std::string randString = fdp.ConsumeRandomLengthString(fdp.remaining_bytes());
+                    dealer->dump(randString.c_str());
+                },
+                [&]() -> void {
+                    size_t allocSize = fdp.ConsumeIntegralInRange<size_t>(0, kMaxAllocSize);
+                    sp<IMemory> allocated = dealer->allocate(allocSize);
+                    // If the allocation was successful, try to write to it
+                    if (allocated != nullptr && allocated->unsecurePointer() != nullptr) {
+                        memset(allocated->unsecurePointer(), 1, allocated->size());
+
+                        // Clear the address from freelist since it has been allocated over again.
+                        free_list.erase(allocated->offset());
+                    }
+                },
+        })();
+    }
+
+    return 0;
+}
+} // namespace android
diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp
index 399a86a..38ae353 100644
--- a/libs/gui/Android.bp
+++ b/libs/gui/Android.bp
@@ -69,7 +69,6 @@
         "IGraphicBufferProducer.cpp",
         "IProducerListener.cpp",
         "IRegionSamplingListener.cpp",
-        "IScreenCaptureListener.cpp",
         "ISurfaceComposer.cpp",
         "ISurfaceComposerClient.cpp",
         "ITransactionCompletedListener.cpp",
@@ -78,6 +77,7 @@
         "LayerState.cpp",
         "OccupancyTracker.cpp",
         "StreamSplitter.cpp",
+        "ScreenCaptureResults.cpp",
         "Surface.cpp",
         "SurfaceControl.cpp",
         "SurfaceComposerClient.cpp",
diff --git a/libs/gui/IScreenCaptureListener.cpp b/libs/gui/IScreenCaptureListener.cpp
deleted file mode 100644
index 0635e9c..0000000
--- a/libs/gui/IScreenCaptureListener.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 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.
- */
-
-#include <gui/IScreenCaptureListener.h>
-#include <gui/LayerState.h>
-
-namespace android {
-
-namespace { // Anonymous
-
-enum class Tag : uint32_t {
-    ON_SCREEN_CAPTURE_COMPLETE = IBinder::FIRST_CALL_TRANSACTION,
-    LAST = ON_SCREEN_CAPTURE_COMPLETE,
-};
-
-} // Anonymous namespace
-
-class BpScreenCaptureListener : public SafeBpInterface<IScreenCaptureListener> {
-public:
-    explicit BpScreenCaptureListener(const sp<IBinder>& impl)
-          : SafeBpInterface<IScreenCaptureListener>(impl, "BpScreenCaptureListener") {}
-
-    ~BpScreenCaptureListener() override;
-
-    status_t onScreenCaptureComplete(const ScreenCaptureResults& captureResults) override {
-        Parcel data, reply;
-        data.writeInterfaceToken(IScreenCaptureListener::getInterfaceDescriptor());
-
-        SAFE_PARCEL(captureResults.write, data);
-        return remote()->transact(static_cast<uint32_t>(Tag::ON_SCREEN_CAPTURE_COMPLETE), data,
-                                  &reply, IBinder::FLAG_ONEWAY);
-    }
-};
-
-// Out-of-line virtual method definitions to trigger vtable emission in this translation unit (see
-// clang warning -Wweak-vtables)
-BpScreenCaptureListener::~BpScreenCaptureListener() = default;
-
-IMPLEMENT_META_INTERFACE(ScreenCaptureListener, "android.gui.IScreenCaptureListener");
-
-status_t BnScreenCaptureListener::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
-                                             uint32_t flags) {
-    auto tag = static_cast<Tag>(code);
-    switch (tag) {
-        case Tag::ON_SCREEN_CAPTURE_COMPLETE: {
-            CHECK_INTERFACE(IScreenCaptureListener, data, reply);
-            ScreenCaptureResults captureResults;
-            SAFE_PARCEL(captureResults.read, data);
-            return onScreenCaptureComplete(captureResults);
-        }
-        default: {
-            return BBinder::onTransact(code, data, reply, flags);
-        }
-    }
-}
-
-} // namespace android
\ No newline at end of file
diff --git a/libs/gui/LayerState.cpp b/libs/gui/LayerState.cpp
index 7d2c7b8..63be3ed 100644
--- a/libs/gui/LayerState.cpp
+++ b/libs/gui/LayerState.cpp
@@ -714,33 +714,4 @@
     return NO_ERROR;
 }
 
-status_t ScreenCaptureResults::write(Parcel& output) const {
-    if (buffer != nullptr) {
-        SAFE_PARCEL(output.writeBool, true);
-        SAFE_PARCEL(output.write, *buffer);
-    } else {
-        SAFE_PARCEL(output.writeBool, false);
-    }
-    SAFE_PARCEL(output.writeBool, capturedSecureLayers);
-    SAFE_PARCEL(output.writeUint32, static_cast<uint32_t>(capturedDataspace));
-    SAFE_PARCEL(output.writeInt32, result);
-    return NO_ERROR;
-}
-
-status_t ScreenCaptureResults::read(const Parcel& input) {
-    bool hasGraphicBuffer;
-    SAFE_PARCEL(input.readBool, &hasGraphicBuffer);
-    if (hasGraphicBuffer) {
-        buffer = new GraphicBuffer();
-        SAFE_PARCEL(input.read, *buffer);
-    }
-
-    SAFE_PARCEL(input.readBool, &capturedSecureLayers);
-    uint32_t dataspace = 0;
-    SAFE_PARCEL(input.readUint32, &dataspace);
-    capturedDataspace = static_cast<ui::Dataspace>(dataspace);
-    SAFE_PARCEL(input.readInt32, &result);
-    return NO_ERROR;
-}
-
 }; // namespace android
diff --git a/libs/gui/ScreenCaptureResults.cpp b/libs/gui/ScreenCaptureResults.cpp
new file mode 100644
index 0000000..2b29487
--- /dev/null
+++ b/libs/gui/ScreenCaptureResults.cpp
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gui/ScreenCaptureResults.h>
+
+namespace android::gui {
+
+status_t ScreenCaptureResults::writeToParcel(android::Parcel* parcel) const {
+    if (buffer != nullptr) {
+        SAFE_PARCEL(parcel->writeBool, true);
+        SAFE_PARCEL(parcel->write, *buffer);
+    } else {
+        SAFE_PARCEL(parcel->writeBool, false);
+    }
+    SAFE_PARCEL(parcel->writeBool, capturedSecureLayers);
+    SAFE_PARCEL(parcel->writeUint32, static_cast<uint32_t>(capturedDataspace));
+    SAFE_PARCEL(parcel->writeInt32, result);
+    return NO_ERROR;
+}
+
+status_t ScreenCaptureResults::readFromParcel(const android::Parcel* parcel) {
+    bool hasGraphicBuffer;
+    SAFE_PARCEL(parcel->readBool, &hasGraphicBuffer);
+    if (hasGraphicBuffer) {
+        buffer = new GraphicBuffer();
+        SAFE_PARCEL(parcel->read, *buffer);
+    }
+
+    SAFE_PARCEL(parcel->readBool, &capturedSecureLayers);
+    uint32_t dataspace = 0;
+    SAFE_PARCEL(parcel->readUint32, &dataspace);
+    capturedDataspace = static_cast<ui::Dataspace>(dataspace);
+    SAFE_PARCEL(parcel->readInt32, &result);
+    return NO_ERROR;
+}
+
+} // namespace android::gui
diff --git a/libs/gui/Surface.cpp b/libs/gui/Surface.cpp
index 1bba5e4..e82f0cc 100644
--- a/libs/gui/Surface.cpp
+++ b/libs/gui/Surface.cpp
@@ -618,29 +618,31 @@
     std::mutex mMutex;
 };
 
+void Surface::getDequeueBufferInputLocked(
+        IGraphicBufferProducer::DequeueBufferInput* dequeueInput) {
+    LOG_ALWAYS_FATAL_IF(dequeueInput == nullptr, "input is null");
+
+    dequeueInput->width = mReqWidth ? mReqWidth : mUserWidth;
+    dequeueInput->height = mReqHeight ? mReqHeight : mUserHeight;
+
+    dequeueInput->format = mReqFormat;
+    dequeueInput->usage = mReqUsage;
+
+    dequeueInput->getTimestamps = mEnableFrameTimestamps;
+}
+
 int Surface::dequeueBuffer(android_native_buffer_t** buffer, int* fenceFd) {
     ATRACE_CALL();
     ALOGV("Surface::dequeueBuffer");
 
-    uint32_t reqWidth;
-    uint32_t reqHeight;
-    PixelFormat reqFormat;
-    uint64_t reqUsage;
-    bool enableFrameTimestamps;
-
+    IGraphicBufferProducer::DequeueBufferInput dqInput;
     {
         Mutex::Autolock lock(mMutex);
         if (mReportRemovedBuffers) {
             mRemovedBuffers.clear();
         }
 
-        reqWidth = mReqWidth ? mReqWidth : mUserWidth;
-        reqHeight = mReqHeight ? mReqHeight : mUserHeight;
-
-        reqFormat = mReqFormat;
-        reqUsage = mReqUsage;
-
-        enableFrameTimestamps = mEnableFrameTimestamps;
+        getDequeueBufferInputLocked(&dqInput);
 
         if (mSharedBufferMode && mAutoRefresh && mSharedBufferSlot !=
                 BufferItem::INVALID_BUFFER_SLOT) {
@@ -658,16 +660,17 @@
     nsecs_t startTime = systemTime();
 
     FrameEventHistoryDelta frameTimestamps;
-    status_t result = mGraphicBufferProducer->dequeueBuffer(&buf, &fence, reqWidth, reqHeight,
-                                                            reqFormat, reqUsage, &mBufferAge,
-                                                            enableFrameTimestamps ? &frameTimestamps
-                                                                                  : nullptr);
+    status_t result = mGraphicBufferProducer->dequeueBuffer(&buf, &fence, dqInput.width,
+                                                            dqInput.height, dqInput.format,
+                                                            dqInput.usage, &mBufferAge,
+                                                            dqInput.getTimestamps ?
+                                                                    &frameTimestamps : nullptr);
     mLastDequeueDuration = systemTime() - startTime;
 
     if (result < 0) {
         ALOGV("dequeueBuffer: IGraphicBufferProducer::dequeueBuffer"
                 "(%d, %d, %d, %#" PRIx64 ") failed: %d",
-                reqWidth, reqHeight, reqFormat, reqUsage, result);
+                dqInput.width, dqInput.height, dqInput.format, dqInput.usage, result);
         return result;
     }
 
@@ -696,7 +699,7 @@
         freeAllBuffers();
     }
 
-    if (enableFrameTimestamps) {
+    if (dqInput.getTimestamps) {
          mFrameEventHistory->applyDelta(frameTimestamps);
     }
 
@@ -739,6 +742,176 @@
     return OK;
 }
 
+int Surface::dequeueBuffers(std::vector<BatchBuffer>* buffers) {
+    using DequeueBufferInput = IGraphicBufferProducer::DequeueBufferInput;
+    using DequeueBufferOutput = IGraphicBufferProducer::DequeueBufferOutput;
+    using CancelBufferInput = IGraphicBufferProducer::CancelBufferInput;
+    using RequestBufferOutput = IGraphicBufferProducer::RequestBufferOutput;
+
+    ATRACE_CALL();
+    ALOGV("Surface::dequeueBuffers");
+
+    if (buffers->size() == 0) {
+        ALOGE("%s: must dequeue at least 1 buffer!", __FUNCTION__);
+        return BAD_VALUE;
+    }
+
+    if (mSharedBufferMode) {
+        ALOGE("%s: batch operation is not supported in shared buffer mode!",
+                __FUNCTION__);
+        return INVALID_OPERATION;
+    }
+
+    size_t numBufferRequested = buffers->size();
+    DequeueBufferInput input;
+
+    {
+        Mutex::Autolock lock(mMutex);
+        if (mReportRemovedBuffers) {
+            mRemovedBuffers.clear();
+        }
+
+        getDequeueBufferInputLocked(&input);
+    } // Drop the lock so that we can still touch the Surface while blocking in IGBP::dequeueBuffers
+
+    std::vector<DequeueBufferInput> dequeueInput(numBufferRequested, input);
+    std::vector<DequeueBufferOutput> dequeueOutput;
+
+    nsecs_t startTime = systemTime();
+
+    status_t result = mGraphicBufferProducer->dequeueBuffers(dequeueInput, &dequeueOutput);
+
+    mLastDequeueDuration = systemTime() - startTime;
+
+    if (result < 0) {
+        ALOGV("%s: IGraphicBufferProducer::dequeueBuffers"
+                "(%d, %d, %d, %#" PRIx64 ") failed: %d",
+                __FUNCTION__, input.width, input.height, input.format, input.usage, result);
+        return result;
+    }
+
+    std::vector<CancelBufferInput> cancelBufferInputs(numBufferRequested);
+    std::vector<status_t> cancelBufferOutputs;
+    for (size_t i = 0; i < numBufferRequested; i++) {
+        cancelBufferInputs[i].slot = dequeueOutput[i].slot;
+        cancelBufferInputs[i].fence = dequeueOutput[i].fence;
+    }
+
+    for (const auto& output : dequeueOutput) {
+        if (output.result < 0) {
+            mGraphicBufferProducer->cancelBuffers(cancelBufferInputs, &cancelBufferOutputs);
+            ALOGV("%s: IGraphicBufferProducer::dequeueBuffers"
+                    "(%d, %d, %d, %#" PRIx64 ") failed: %d",
+                    __FUNCTION__, input.width, input.height, input.format, input.usage,
+                    output.result);
+            return output.result;
+        }
+
+        if (output.slot < 0 || output.slot >= NUM_BUFFER_SLOTS) {
+            mGraphicBufferProducer->cancelBuffers(cancelBufferInputs, &cancelBufferOutputs);
+            ALOGE("%s: IGraphicBufferProducer returned invalid slot number %d",
+                    __FUNCTION__, output.slot);
+            android_errorWriteLog(0x534e4554, "36991414"); // SafetyNet logging
+            return FAILED_TRANSACTION;
+        }
+
+        if (input.getTimestamps && !output.timestamps.has_value()) {
+            mGraphicBufferProducer->cancelBuffers(cancelBufferInputs, &cancelBufferOutputs);
+            ALOGE("%s: no frame timestamp returns!", __FUNCTION__);
+            return FAILED_TRANSACTION;
+        }
+
+        // this should never happen
+        ALOGE_IF(output.fence == nullptr,
+                "%s: received null Fence! slot=%d", __FUNCTION__, output.slot);
+    }
+
+    Mutex::Autolock lock(mMutex);
+
+    // Write this while holding the mutex
+    mLastDequeueStartTime = startTime;
+
+    std::vector<int32_t> requestBufferSlots;
+    requestBufferSlots.reserve(numBufferRequested);
+    // handle release all buffers and request buffers
+    for (const auto& output : dequeueOutput) {
+        if (output.result & IGraphicBufferProducer::RELEASE_ALL_BUFFERS) {
+            ALOGV("%s: RELEASE_ALL_BUFFERS during batch operation", __FUNCTION__);
+            freeAllBuffers();
+            break;
+        }
+    }
+
+    for (const auto& output : dequeueOutput) {
+        // Collect slots that needs requesting buffer
+        sp<GraphicBuffer>& gbuf(mSlots[output.slot].buffer);
+        if ((result & IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) || gbuf == nullptr) {
+            if (mReportRemovedBuffers && (gbuf != nullptr)) {
+                mRemovedBuffers.push_back(gbuf);
+            }
+            requestBufferSlots.push_back(output.slot);
+        }
+    }
+
+    // Batch request Buffer
+    std::vector<RequestBufferOutput> reqBufferOutput;
+    if (requestBufferSlots.size() > 0) {
+        result = mGraphicBufferProducer->requestBuffers(requestBufferSlots, &reqBufferOutput);
+        if (result != NO_ERROR) {
+            ALOGE("%s: IGraphicBufferProducer::requestBuffers failed: %d",
+                    __FUNCTION__, result);
+            mGraphicBufferProducer->cancelBuffers(cancelBufferInputs, &cancelBufferOutputs);
+            return result;
+        }
+
+        // Check if we have any single failure
+        for (size_t i = 0; i < requestBufferSlots.size(); i++) {
+            if (reqBufferOutput[i].result != OK) {
+                ALOGE("%s: IGraphicBufferProducer::requestBuffers failed at %zu-th buffer, slot %d",
+                        __FUNCTION__, i, requestBufferSlots[i]);
+                mGraphicBufferProducer->cancelBuffers(cancelBufferInputs, &cancelBufferOutputs);
+                return reqBufferOutput[i].result;
+            }
+        }
+
+        // Fill request buffer results to mSlots
+        for (size_t i = 0; i < requestBufferSlots.size(); i++) {
+            mSlots[requestBufferSlots[i]].buffer = reqBufferOutput[i].buffer;
+        }
+    }
+
+    for (size_t batchIdx = 0; batchIdx < numBufferRequested; batchIdx++) {
+        const auto& output = dequeueOutput[batchIdx];
+        int slot = output.slot;
+        sp<GraphicBuffer>& gbuf(mSlots[slot].buffer);
+
+        if (CC_UNLIKELY(atrace_is_tag_enabled(ATRACE_TAG_GRAPHICS))) {
+            static FenceMonitor hwcReleaseThread("HWC release");
+            hwcReleaseThread.queueFence(output.fence);
+        }
+
+        if (input.getTimestamps) {
+             mFrameEventHistory->applyDelta(output.timestamps.value());
+        }
+
+        if (output.fence->isValid()) {
+            buffers->at(batchIdx).fenceFd = output.fence->dup();
+            if (buffers->at(batchIdx).fenceFd == -1) {
+                ALOGE("%s: error duping fence: %d", __FUNCTION__, errno);
+                // dup() should never fail; something is badly wrong. Soldier on
+                // and hope for the best; the worst that should happen is some
+                // visible corruption that lasts until the next frame.
+            }
+        } else {
+            buffers->at(batchIdx).fenceFd = -1;
+        }
+
+        buffers->at(batchIdx).buffer = gbuf.get();
+        mDequeuedSlots.insert(slot);
+    }
+    return OK;
+}
+
 int Surface::cancelBuffer(android_native_buffer_t* buffer,
         int fenceFd) {
     ATRACE_CALL();
@@ -769,15 +942,65 @@
     return OK;
 }
 
+int Surface::cancelBuffers(const std::vector<BatchBuffer>& buffers) {
+    using CancelBufferInput = IGraphicBufferProducer::CancelBufferInput;
+    ATRACE_CALL();
+    ALOGV("Surface::cancelBuffers");
+
+    if (mSharedBufferMode) {
+        ALOGE("%s: batch operation is not supported in shared buffer mode!",
+                __FUNCTION__);
+        return INVALID_OPERATION;
+    }
+
+    size_t numBuffers = buffers.size();
+    std::vector<CancelBufferInput> cancelBufferInputs(numBuffers);
+    std::vector<status_t> cancelBufferOutputs;
+    size_t numBuffersCancelled = 0;
+    int badSlotResult = 0;
+    for (size_t i = 0; i < numBuffers; i++) {
+        int slot = getSlotFromBufferLocked(buffers[i].buffer);
+        int fenceFd = buffers[i].fenceFd;
+        if (slot < 0) {
+            if (fenceFd >= 0) {
+                close(fenceFd);
+            }
+            ALOGE("%s: cannot find slot number for cancelled buffer", __FUNCTION__);
+            badSlotResult = slot;
+        } else {
+            sp<Fence> fence(fenceFd >= 0 ? new Fence(fenceFd) : Fence::NO_FENCE);
+            cancelBufferInputs[numBuffersCancelled].slot = slot;
+            cancelBufferInputs[numBuffersCancelled++].fence = fence;
+        }
+    }
+    cancelBufferInputs.resize(numBuffersCancelled);
+    mGraphicBufferProducer->cancelBuffers(cancelBufferInputs, &cancelBufferOutputs);
+
+
+    for (size_t i = 0; i < numBuffersCancelled; i++) {
+        mDequeuedSlots.erase(cancelBufferInputs[i].slot);
+    }
+
+    if (badSlotResult != 0) {
+        return badSlotResult;
+    }
+    return OK;
+}
+
 int Surface::getSlotFromBufferLocked(
         android_native_buffer_t* buffer) const {
+    if (buffer == nullptr) {
+        ALOGE("%s: input buffer is null!", __FUNCTION__);
+        return BAD_VALUE;
+    }
+
     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
         if (mSlots[i].buffer != nullptr &&
                 mSlots[i].buffer->handle == buffer->handle) {
             return i;
         }
     }
-    ALOGE("getSlotFromBufferLocked: unknown buffer: %p", buffer->handle);
+    ALOGE("%s: unknown buffer: %p", __FUNCTION__, buffer->handle);
     return BAD_VALUE;
 }
 
@@ -787,42 +1010,22 @@
     return OK;
 }
 
-int Surface::queueBuffer(android_native_buffer_t* buffer, int fenceFd) {
-    ATRACE_CALL();
-    ALOGV("Surface::queueBuffer");
-    Mutex::Autolock lock(mMutex);
-    int64_t timestamp;
+void Surface::getQueueBufferInputLocked(android_native_buffer_t* buffer, int fenceFd,
+        nsecs_t timestamp, IGraphicBufferProducer::QueueBufferInput* out) {
     bool isAutoTimestamp = false;
 
-    if (mTimestamp == NATIVE_WINDOW_TIMESTAMP_AUTO) {
+    if (timestamp == NATIVE_WINDOW_TIMESTAMP_AUTO) {
         timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
         isAutoTimestamp = true;
         ALOGV("Surface::queueBuffer making up timestamp: %.2f ms",
             timestamp / 1000000.0);
-    } else {
-        timestamp = mTimestamp;
     }
-    int i = getSlotFromBufferLocked(buffer);
-    if (i < 0) {
-        if (fenceFd >= 0) {
-            close(fenceFd);
-        }
-        return i;
-    }
-    if (mSharedBufferSlot == i && mSharedBufferHasBeenQueued) {
-        if (fenceFd >= 0) {
-            close(fenceFd);
-        }
-        return OK;
-    }
-
 
     // Make sure the crop rectangle is entirely inside the buffer.
     Rect crop(Rect::EMPTY_RECT);
     mCrop.intersect(Rect(buffer->width, buffer->height), &crop);
 
     sp<Fence> fence(fenceFd >= 0 ? new Fence(fenceFd) : Fence::NO_FENCE);
-    IGraphicBufferProducer::QueueBufferOutput output;
     IGraphicBufferProducer::QueueBufferInput input(timestamp, isAutoTimestamp,
             static_cast<android_dataspace>(mDataSpace), crop, mScalingMode,
             mTransform ^ mStickyTransform, fence, mStickyTransform,
@@ -893,15 +1096,12 @@
 
         input.setSurfaceDamage(flippedRegion);
     }
+    *out = input;
+}
 
-    nsecs_t now = systemTime();
-    status_t err = mGraphicBufferProducer->queueBuffer(i, input, &output);
-    mLastQueueDuration = systemTime() - now;
-    if (err != OK)  {
-        ALOGE("queueBuffer: error queuing buffer to SurfaceTexture, %d", err);
-    }
-
-    mDequeuedSlots.erase(i);
+void Surface::onBufferQueuedLocked(int slot, sp<Fence> fence,
+        const IGraphicBufferProducer::QueueBufferOutput& output) {
+    mDequeuedSlots.erase(slot);
 
     if (mEnableFrameTimestamps) {
         mFrameEventHistory->applyDelta(output.frameTimestamps);
@@ -935,7 +1135,7 @@
         mDirtyRegion = Region::INVALID_REGION;
     }
 
-    if (mSharedBufferMode && mAutoRefresh && mSharedBufferSlot == i) {
+    if (mSharedBufferMode && mAutoRefresh && mSharedBufferSlot == slot) {
         mSharedBufferHasBeenQueued = true;
     }
 
@@ -945,6 +1145,89 @@
         static FenceMonitor gpuCompletionThread("GPU completion");
         gpuCompletionThread.queueFence(fence);
     }
+}
+
+int Surface::queueBuffer(android_native_buffer_t* buffer, int fenceFd) {
+    ATRACE_CALL();
+    ALOGV("Surface::queueBuffer");
+    Mutex::Autolock lock(mMutex);
+
+    int i = getSlotFromBufferLocked(buffer);
+    if (i < 0) {
+        if (fenceFd >= 0) {
+            close(fenceFd);
+        }
+        return i;
+    }
+    if (mSharedBufferSlot == i && mSharedBufferHasBeenQueued) {
+        if (fenceFd >= 0) {
+            close(fenceFd);
+        }
+        return OK;
+    }
+
+    IGraphicBufferProducer::QueueBufferOutput output;
+    IGraphicBufferProducer::QueueBufferInput input;
+    getQueueBufferInputLocked(buffer, fenceFd, mTimestamp, &input);
+    sp<Fence> fence = input.fence;
+
+    nsecs_t now = systemTime();
+    status_t err = mGraphicBufferProducer->queueBuffer(i, input, &output);
+    mLastQueueDuration = systemTime() - now;
+    if (err != OK)  {
+        ALOGE("queueBuffer: error queuing buffer, %d", err);
+    }
+
+    onBufferQueuedLocked(i, fence, output);
+    return err;
+}
+
+int Surface::queueBuffers(const std::vector<BatchQueuedBuffer>& buffers) {
+    ATRACE_CALL();
+    ALOGV("Surface::queueBuffers");
+    Mutex::Autolock lock(mMutex);
+
+    if (mSharedBufferMode) {
+        ALOGE("%s: batched operation is not supported in shared buffer mode", __FUNCTION__);
+        return INVALID_OPERATION;
+    }
+
+    size_t numBuffers = buffers.size();
+    std::vector<IGraphicBufferProducer::QueueBufferInput> queueBufferInputs(numBuffers);
+    std::vector<IGraphicBufferProducer::QueueBufferOutput> queueBufferOutputs;
+    std::vector<int> bufferSlots(numBuffers, -1);
+    std::vector<sp<Fence>> bufferFences(numBuffers);
+
+    for (size_t batchIdx = 0; batchIdx < numBuffers; batchIdx++) {
+        int i = getSlotFromBufferLocked(buffers[batchIdx].buffer);
+        if (i < 0) {
+            if (buffers[batchIdx].fenceFd >= 0) {
+                close(buffers[batchIdx].fenceFd);
+            }
+            return i;
+        }
+        bufferSlots[batchIdx] = i;
+
+        IGraphicBufferProducer::QueueBufferInput input;
+        getQueueBufferInputLocked(
+                buffers[batchIdx].buffer, buffers[batchIdx].fenceFd, buffers[batchIdx].timestamp,
+                &input);
+        bufferFences[batchIdx] = input.fence;
+        queueBufferInputs[batchIdx] = input;
+    }
+
+    nsecs_t now = systemTime();
+    status_t err = mGraphicBufferProducer->queueBuffers(queueBufferInputs, &queueBufferOutputs);
+    mLastQueueDuration = systemTime() - now;
+    if (err != OK)  {
+        ALOGE("%s: error queuing buffer, %d", __FUNCTION__, err);
+    }
+
+
+    for (size_t batchIdx = 0; batchIdx < numBuffers; batchIdx++) {
+        onBufferQueuedLocked(bufferSlots[batchIdx], bufferFences[batchIdx],
+                queueBufferOutputs[batchIdx]);
+    }
 
     return err;
 }
diff --git a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplay.cpp b/libs/gui/aidl/android/gui/IScreenCaptureListener.aidl
similarity index 66%
copy from services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplay.cpp
copy to libs/gui/aidl/android/gui/IScreenCaptureListener.aidl
index c9788af..f490118 100644
--- a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplay.cpp
+++ b/libs/gui/aidl/android/gui/IScreenCaptureListener.aidl
@@ -1,5 +1,5 @@
 /*
- * Copyright 2019 The Android Open Source Project
+ * Copyright 2021 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,12 +14,11 @@
  * limitations under the License.
  */
 
-#include "mock/DisplayHardware/MockDisplay.h"
+package android.gui;
 
-namespace android::Hwc2::mock {
+import android.gui.ScreenCaptureResults;
 
-// Explicit default instantiation is recommended.
-Display::Display() = default;
-Display::~Display() = default;
-
-} // namespace android::Hwc2::mock
\ No newline at end of file
+/** @hide */
+oneway interface IScreenCaptureListener {
+    void onScreenCaptureComplete(in ScreenCaptureResults captureResults);
+}
\ No newline at end of file
diff --git a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplay.cpp b/libs/gui/aidl/android/gui/ScreenCaptureResults.aidl
similarity index 66%
rename from services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplay.cpp
rename to libs/gui/aidl/android/gui/ScreenCaptureResults.aidl
index c9788af..9908edd 100644
--- a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplay.cpp
+++ b/libs/gui/aidl/android/gui/ScreenCaptureResults.aidl
@@ -1,5 +1,5 @@
 /*
- * Copyright 2019 The Android Open Source Project
+ * Copyright 2021 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,12 +14,6 @@
  * limitations under the License.
  */
 
-#include "mock/DisplayHardware/MockDisplay.h"
+package android.gui;
 
-namespace android::Hwc2::mock {
-
-// Explicit default instantiation is recommended.
-Display::Display() = default;
-Display::~Display() = default;
-
-} // namespace android::Hwc2::mock
\ No newline at end of file
+parcelable ScreenCaptureResults cpp_header "gui/ScreenCaptureResults.h";
\ No newline at end of file
diff --git a/libs/gui/include/gui/IScreenCaptureListener.h b/libs/gui/include/gui/IScreenCaptureListener.h
deleted file mode 100644
index a2ddc9f..0000000
--- a/libs/gui/include/gui/IScreenCaptureListener.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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 <binder/Binder.h>
-#include <binder/IInterface.h>
-#include <binder/Parcel.h>
-#include <binder/SafeInterface.h>
-
-namespace android {
-
-struct ScreenCaptureResults;
-
-// TODO(b/166271443): Convert to AIDL
-class IScreenCaptureListener : public IInterface {
-public:
-    DECLARE_META_INTERFACE(ScreenCaptureListener)
-
-    virtual status_t onScreenCaptureComplete(const ScreenCaptureResults& captureResults) = 0;
-};
-
-class BnScreenCaptureListener : public SafeBnInterface<IScreenCaptureListener> {
-public:
-    BnScreenCaptureListener()
-          : SafeBnInterface<IScreenCaptureListener>("BnScreenCaptureListener") {}
-
-    status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply,
-                        uint32_t flags = 0) override;
-};
-
-} // namespace android
diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h
index 40316db..86f3c60 100644
--- a/libs/gui/include/gui/ISurfaceComposer.h
+++ b/libs/gui/include/gui/ISurfaceComposer.h
@@ -22,8 +22,8 @@
 #include <binder/IBinder.h>
 #include <binder/IInterface.h>
 
+#include <android/gui/IScreenCaptureListener.h>
 #include <android/gui/ITransactionTraceListener.h>
-#include <gui/IScreenCaptureListener.h>
 #include <gui/ITransactionCompletedListener.h>
 
 #include <input/Flags.h>
@@ -59,7 +59,6 @@
 struct DisplayState;
 struct InputWindowCommands;
 struct LayerCaptureArgs;
-struct ScreenCaptureResults;
 class LayerDebugInfo;
 class HdrCapabilities;
 class IDisplayEventConnection;
@@ -69,6 +68,8 @@
 class Rect;
 enum class FrameEvent;
 
+using gui::IScreenCaptureListener;
+
 namespace ui {
 
 struct DisplayState;
diff --git a/libs/gui/include/gui/LayerState.h b/libs/gui/include/gui/LayerState.h
index f1c5d67..4a291ae 100644
--- a/libs/gui/include/gui/LayerState.h
+++ b/libs/gui/include/gui/LayerState.h
@@ -362,16 +362,6 @@
     status_t read(const Parcel& input) override;
 };
 
-struct ScreenCaptureResults {
-    sp<GraphicBuffer> buffer;
-    bool capturedSecureLayers{false};
-    ui::Dataspace capturedDataspace{ui::Dataspace::V0_SRGB};
-    status_t result = OK;
-
-    status_t write(Parcel& output) const;
-    status_t read(const Parcel& input);
-};
-
 }; // namespace android
 
 #endif // ANDROID_SF_LAYER_STATE_H
diff --git a/libs/gui/include/gui/ScreenCaptureResults.h b/libs/gui/include/gui/ScreenCaptureResults.h
new file mode 100644
index 0000000..fdb4b69
--- /dev/null
+++ b/libs/gui/include/gui/ScreenCaptureResults.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#define SAFE_PARCEL(FUNC, ...)                                                            \
+    {                                                                                     \
+        status_t error = FUNC(__VA_ARGS__);                                               \
+        if (error) {                                                                      \
+            ALOGE("ERROR(%d). Failed to call parcel %s(%s)", error, #FUNC, #__VA_ARGS__); \
+            return error;                                                                 \
+        }                                                                                 \
+    }
+
+#include <binder/Parcel.h>
+#include <binder/Parcelable.h>
+#include <ui/GraphicBuffer.h>
+
+namespace android::gui {
+
+struct ScreenCaptureResults : public Parcelable {
+public:
+    ScreenCaptureResults() = default;
+    virtual ~ScreenCaptureResults() = default;
+    status_t writeToParcel(android::Parcel* parcel) const override;
+    status_t readFromParcel(const android::Parcel* parcel) override;
+
+    sp<GraphicBuffer> buffer;
+    bool capturedSecureLayers{false};
+    ui::Dataspace capturedDataspace{ui::Dataspace::V0_SRGB};
+    status_t result = OK;
+};
+
+} // namespace android::gui
diff --git a/libs/gui/include/gui/Surface.h b/libs/gui/include/gui/Surface.h
index 82bc5c9..43b5dcd 100644
--- a/libs/gui/include/gui/Surface.h
+++ b/libs/gui/include/gui/Surface.h
@@ -344,6 +344,23 @@
     static status_t attachAndQueueBufferWithDataspace(Surface* surface, sp<GraphicBuffer> buffer,
                                                       ui::Dataspace dataspace);
 
+    // Batch version of dequeueBuffer, cancelBuffer and queueBuffer
+    // Note that these batched operations are not supported when shared buffer mode is being used.
+    struct BatchBuffer {
+        ANativeWindowBuffer* buffer = nullptr;
+        int fenceFd = -1;
+    };
+    virtual int dequeueBuffers(std::vector<BatchBuffer>* buffers);
+    virtual int cancelBuffers(const std::vector<BatchBuffer>& buffers);
+
+    struct BatchQueuedBuffer {
+        ANativeWindowBuffer* buffer = nullptr;
+        int fenceFd = -1;
+        nsecs_t timestamp = NATIVE_WINDOW_TIMESTAMP_AUTO;
+    };
+    virtual int queueBuffers(
+            const std::vector<BatchQueuedBuffer>& buffers);
+
 protected:
     enum { NUM_BUFFER_SLOTS = BufferQueueDefs::NUM_BUFFER_SLOTS };
     enum { DEFAULT_FORMAT = PIXEL_FORMAT_RGBA_8888 };
@@ -373,6 +390,14 @@
     void freeAllBuffers();
     int getSlotFromBufferLocked(android_native_buffer_t* buffer) const;
 
+    void getDequeueBufferInputLocked(IGraphicBufferProducer::DequeueBufferInput* dequeueInput);
+
+    void getQueueBufferInputLocked(android_native_buffer_t* buffer, int fenceFd, nsecs_t timestamp,
+            IGraphicBufferProducer::QueueBufferInput* out);
+
+    void onBufferQueuedLocked(int slot, sp<Fence> fence,
+            const IGraphicBufferProducer::QueueBufferOutput& output);
+
     struct BufferSlot {
         sp<GraphicBuffer> buffer;
         Region dirtyRegion;
diff --git a/libs/gui/include/gui/SyncScreenCaptureListener.h b/libs/gui/include/gui/SyncScreenCaptureListener.h
index 2857996..8620b77 100644
--- a/libs/gui/include/gui/SyncScreenCaptureListener.h
+++ b/libs/gui/include/gui/SyncScreenCaptureListener.h
@@ -16,16 +16,19 @@
 
 #pragma once
 
+#include <android/gui/BnScreenCaptureListener.h>
 #include <gui/SurfaceComposerClient.h>
 #include <future>
 
 namespace android {
 
-class SyncScreenCaptureListener : public BnScreenCaptureListener {
+using gui::ScreenCaptureResults;
+
+struct SyncScreenCaptureListener : gui::BnScreenCaptureListener {
 public:
-    status_t onScreenCaptureComplete(const ScreenCaptureResults& captureResults) override {
+    binder::Status onScreenCaptureComplete(const ScreenCaptureResults& captureResults) override {
         resultsPromise.set_value(captureResults);
-        return NO_ERROR;
+        return binder::Status::ok();
     }
 
     ScreenCaptureResults waitForResults() {
diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp
index fa98cd4c..63db9a7 100644
--- a/libs/gui/tests/Surface_test.cpp
+++ b/libs/gui/tests/Surface_test.cpp
@@ -2024,4 +2024,86 @@
     EXPECT_EQ(BufferQueueDefs::NUM_BUFFER_SLOTS, count);
 }
 
+TEST_F(SurfaceTest, BatchOperations) {
+    const int BUFFER_COUNT = 16;
+    const int BATCH_SIZE = 8;
+    sp<IGraphicBufferProducer> producer;
+    sp<IGraphicBufferConsumer> consumer;
+    BufferQueue::createBufferQueue(&producer, &consumer);
+
+    sp<CpuConsumer> cpuConsumer = new CpuConsumer(consumer, 1);
+    sp<Surface> surface = new Surface(producer);
+    sp<ANativeWindow> window(surface);
+    sp<StubProducerListener> listener = new StubProducerListener();
+
+    ASSERT_EQ(OK, surface->connect(NATIVE_WINDOW_API_CPU, /*listener*/listener,
+            /*reportBufferRemoval*/false));
+
+    ASSERT_EQ(NO_ERROR, native_window_set_buffer_count(window.get(), BUFFER_COUNT));
+
+    std::vector<Surface::BatchBuffer> buffers(BATCH_SIZE);
+
+    // Batch dequeued buffers can be queued individually
+    ASSERT_EQ(NO_ERROR, surface->dequeueBuffers(&buffers));
+    for (size_t i = 0; i < BATCH_SIZE; i++) {
+        ANativeWindowBuffer* buffer = buffers[i].buffer;
+        int fence = buffers[i].fenceFd;
+        ASSERT_EQ(NO_ERROR, window->queueBuffer(window.get(), buffer, fence));
+    }
+
+    // Batch dequeued buffers can be canceled individually
+    ASSERT_EQ(NO_ERROR, surface->dequeueBuffers(&buffers));
+    for (size_t i = 0; i < BATCH_SIZE; i++) {
+        ANativeWindowBuffer* buffer = buffers[i].buffer;
+        int fence = buffers[i].fenceFd;
+        ASSERT_EQ(NO_ERROR, window->cancelBuffer(window.get(), buffer, fence));
+    }
+
+    // Batch dequeued buffers can be batch cancelled
+    ASSERT_EQ(NO_ERROR, surface->dequeueBuffers(&buffers));
+    ASSERT_EQ(NO_ERROR, surface->cancelBuffers(buffers));
+
+    // Batch dequeued buffers can be batch queued
+    ASSERT_EQ(NO_ERROR, surface->dequeueBuffers(&buffers));
+    std::vector<Surface::BatchQueuedBuffer> queuedBuffers(BATCH_SIZE);
+    for (size_t i = 0; i < BATCH_SIZE; i++) {
+        queuedBuffers[i].buffer = buffers[i].buffer;
+        queuedBuffers[i].fenceFd = buffers[i].fenceFd;
+        queuedBuffers[i].timestamp = NATIVE_WINDOW_TIMESTAMP_AUTO;
+    }
+    ASSERT_EQ(NO_ERROR, surface->queueBuffers(queuedBuffers));
+
+    ASSERT_EQ(NO_ERROR, surface->disconnect(NATIVE_WINDOW_API_CPU));
+}
+
+TEST_F(SurfaceTest, BatchIllegalOperations) {
+    const int BUFFER_COUNT = 16;
+    const int BATCH_SIZE = 8;
+    sp<IGraphicBufferProducer> producer;
+    sp<IGraphicBufferConsumer> consumer;
+    BufferQueue::createBufferQueue(&producer, &consumer);
+
+    sp<CpuConsumer> cpuConsumer = new CpuConsumer(consumer, 1);
+    sp<Surface> surface = new Surface(producer);
+    sp<ANativeWindow> window(surface);
+    sp<StubProducerListener> listener = new StubProducerListener();
+
+    ASSERT_EQ(OK, surface->connect(NATIVE_WINDOW_API_CPU, /*listener*/listener,
+            /*reportBufferRemoval*/false));
+
+    ASSERT_EQ(NO_ERROR, native_window_set_buffer_count(window.get(), BUFFER_COUNT));
+
+    std::vector<Surface::BatchBuffer> buffers(BATCH_SIZE);
+    std::vector<Surface::BatchQueuedBuffer> queuedBuffers(BATCH_SIZE);
+
+    // Batch operations are invalid in shared buffer mode
+    surface->setSharedBufferMode(true);
+    ASSERT_EQ(INVALID_OPERATION, surface->dequeueBuffers(&buffers));
+    ASSERT_EQ(INVALID_OPERATION, surface->cancelBuffers(buffers));
+    ASSERT_EQ(INVALID_OPERATION, surface->queueBuffers(queuedBuffers));
+    surface->setSharedBufferMode(false);
+
+    ASSERT_EQ(NO_ERROR, surface->disconnect(NATIVE_WINDOW_API_CPU));
+}
+
 } // namespace android
diff --git a/libs/nativewindow/Android.bp b/libs/nativewindow/Android.bp
index 07e5d86..3011dcc 100644
--- a/libs/nativewindow/Android.bp
+++ b/libs/nativewindow/Android.bp
@@ -28,6 +28,7 @@
     // TODO(b/153609531): remove when no longer needed.
     native_bridge_supported: true,
     min_sdk_version: "29",
+    host_supported: true,
 }
 
 ndk_library {
diff --git a/services/inputflinger/benchmarks/InputDispatcher_benchmarks.cpp b/services/inputflinger/benchmarks/InputDispatcher_benchmarks.cpp
index 4e55872..887bdd4 100644
--- a/services/inputflinger/benchmarks/InputDispatcher_benchmarks.cpp
+++ b/services/inputflinger/benchmarks/InputDispatcher_benchmarks.cpp
@@ -55,12 +55,18 @@
         ALOGE("There is no focused window for %s", applicationHandle->getName().c_str());
     }
 
-    void notifyConnectionUnresponsive(const sp<IBinder>& connectionToken,
-                                      const std::string& reason) override {
-        ALOGE("Connection is not responding: %s", reason.c_str());
+    void notifyWindowUnresponsive(const sp<IBinder>& connectionToken,
+                                  const std::string& reason) override {
+        ALOGE("Window is not responding: %s", reason.c_str());
     }
 
-    void notifyConnectionResponsive(const sp<IBinder>& connectionToken) override {}
+    void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {}
+
+    void notifyMonitorUnresponsive(int32_t pid, const std::string& reason) override {
+        ALOGE("Monitor is not responding: %s", reason.c_str());
+    }
+
+    void notifyMonitorResponsive(int32_t pid) override {}
 
     void notifyInputChannelBroken(const sp<IBinder>&) override {}
 
diff --git a/services/inputflinger/dispatcher/Entry.h b/services/inputflinger/dispatcher/Entry.h
index 3a860f0..26b641d 100644
--- a/services/inputflinger/dispatcher/Entry.h
+++ b/services/inputflinger/dispatcher/Entry.h
@@ -271,6 +271,7 @@
     sp<IBinder> newToken;
     std::string obscuringPackage;
     bool enabled;
+    int32_t pid;
 };
 
 } // namespace android::inputdispatcher
diff --git a/services/inputflinger/dispatcher/InputDispatcher.cpp b/services/inputflinger/dispatcher/InputDispatcher.cpp
index 0c286ce..cdc74f3 100644
--- a/services/inputflinger/dispatcher/InputDispatcher.cpp
+++ b/services/inputflinger/dispatcher/InputDispatcher.cpp
@@ -453,6 +453,20 @@
     return event;
 }
 
+static std::optional<int32_t> findMonitorPidByToken(
+        const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
+        const sp<IBinder>& token) {
+    for (const auto& it : monitorsByDisplay) {
+        const std::vector<Monitor>& monitors = it.second;
+        for (const Monitor& monitor : monitors) {
+            if (monitor.inputChannel->getConnectionToken() == token) {
+                return monitor.pid;
+            }
+        }
+    }
+    return std::nullopt;
+}
+
 // --- InputDispatcher ---
 
 InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
@@ -615,7 +629,7 @@
     connection->responsive = false;
     // Stop waking up for this unresponsive connection
     mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
-    onAnrLocked(*connection);
+    onAnrLocked(connection);
     return LONG_LONG_MIN;
 }
 
@@ -5154,6 +5168,14 @@
     return std::nullopt;
 }
 
+std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
+    std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
+    if (gesturePid.has_value()) {
+        return gesturePid;
+    }
+    return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
+}
+
 sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
     if (inputConnectionToken == nullptr) {
         return nullptr;
@@ -5214,12 +5236,15 @@
     postCommandLocked(std::move(commandEntry));
 }
 
-void InputDispatcher::onAnrLocked(const Connection& connection) {
+void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
+    if (connection == nullptr) {
+        LOG_ALWAYS_FATAL("Caller must check for nullness");
+    }
     // Since we are allowing the policy to extend the timeout, maybe the waitQueue
     // is already healthy again. Don't raise ANR in this situation
-    if (connection.waitQueue.empty()) {
+    if (connection->waitQueue.empty()) {
         ALOGI("Not raising ANR because the connection %s has recovered",
-              connection.inputChannel->getName().c_str());
+              connection->inputChannel->getName().c_str());
         return;
     }
     /**
@@ -5230,21 +5255,20 @@
      * processes the events linearly. So providing information about the oldest entry seems to be
      * most useful.
      */
-    DispatchEntry* oldestEntry = *connection.waitQueue.begin();
+    DispatchEntry* oldestEntry = *connection->waitQueue.begin();
     const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
     std::string reason =
             android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
-                                        connection.inputChannel->getName().c_str(),
+                                        connection->inputChannel->getName().c_str(),
                                         ns2ms(currentWait),
                                         oldestEntry->eventEntry->getDescription().c_str());
-    sp<IBinder> connectionToken = connection.inputChannel->getConnectionToken();
+    sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
     updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
 
-    std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
-            &InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible);
-    commandEntry->connectionToken = connectionToken;
-    commandEntry->reason = std::move(reason);
-    postCommandLocked(std::move(commandEntry));
+    processConnectionUnresponsiveLocked(*connection, std::move(reason));
+
+    // Stop waking up for events on this connection, it is already unresponsive
+    cancelEventsForAnrLocked(connection);
 }
 
 void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
@@ -5329,26 +5353,34 @@
     mLock.lock();
 }
 
-void InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible(
-        CommandEntry* commandEntry) {
+void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
     mLock.unlock();
 
-    mPolicy->notifyConnectionUnresponsive(commandEntry->connectionToken, commandEntry->reason);
+    mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
 
     mLock.lock();
-
-    // stop waking up for events in this connection, it is already not responding
-    sp<Connection> connection = getConnectionLocked(commandEntry->connectionToken);
-    if (connection == nullptr) {
-        return;
-    }
-    cancelEventsForAnrLocked(connection);
 }
 
-void InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible(CommandEntry* commandEntry) {
+void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
     mLock.unlock();
 
-    mPolicy->notifyConnectionResponsive(commandEntry->connectionToken);
+    mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
+
+    mLock.lock();
+}
+
+void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
+    mLock.unlock();
+
+    mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
+
+    mLock.lock();
+}
+
+void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
+    mLock.unlock();
+
+    mPolicy->notifyMonitorResponsive(commandEntry->pid);
 
     mLock.lock();
 }
@@ -5453,13 +5485,8 @@
         if (!connection->responsive) {
             connection->responsive = isConnectionResponsive(*connection);
             if (connection->responsive) {
-                // The connection was unresponsive, and now it's responsive. Tell the policy
-                // about it so that it can stop ANR.
-                std::unique_ptr<CommandEntry> connectionResponsiveCommand =
-                        std::make_unique<CommandEntry>(
-                                &InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible);
-                connectionResponsiveCommand->connectionToken = connectionToken;
-                postCommandLocked(std::move(connectionResponsiveCommand));
+                // The connection was unresponsive, and now it's responsive.
+                processConnectionResponsiveLocked(*connection);
             }
         }
         traceWaitQueueLength(connection);
@@ -5475,6 +5502,82 @@
     startDispatchCycleLocked(now(), connection);
 }
 
+void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
+    std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
+            &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
+    monitorUnresponsiveCommand->pid = pid;
+    monitorUnresponsiveCommand->reason = std::move(reason);
+    postCommandLocked(std::move(monitorUnresponsiveCommand));
+}
+
+void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
+                                                          std::string reason) {
+    std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
+            &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
+    windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
+    windowUnresponsiveCommand->reason = std::move(reason);
+    postCommandLocked(std::move(windowUnresponsiveCommand));
+}
+
+void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
+    std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
+            &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
+    monitorResponsiveCommand->pid = pid;
+    postCommandLocked(std::move(monitorResponsiveCommand));
+}
+
+void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
+    std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
+            &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
+    windowResponsiveCommand->connectionToken = std::move(connectionToken);
+    postCommandLocked(std::move(windowResponsiveCommand));
+}
+
+/**
+ * Tell the policy that a connection has become unresponsive so that it can start ANR.
+ * Check whether the connection of interest is a monitor or a window, and add the corresponding
+ * command entry to the command queue.
+ */
+void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
+                                                          std::string reason) {
+    const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
+    if (connection.monitor) {
+        ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
+              reason.c_str());
+        std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
+        if (!pid.has_value()) {
+            ALOGE("Could not find unresponsive monitor for connection %s",
+                  connection.inputChannel->getName().c_str());
+            return;
+        }
+        sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
+        return;
+    }
+    // If not a monitor, must be a window
+    ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
+          reason.c_str());
+    sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
+}
+
+/**
+ * Tell the policy that a connection has become responsive so that it can stop ANR.
+ */
+void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
+    const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
+    if (connection.monitor) {
+        std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
+        if (!pid.has_value()) {
+            ALOGE("Could not find responsive monitor for connection %s",
+                  connection.inputChannel->getName().c_str());
+            return;
+        }
+        sendMonitorResponsiveCommandLocked(pid.value());
+        return;
+    }
+    // If not a monitor, must be a window
+    sendWindowResponsiveCommandLocked(connectionToken);
+}
+
 bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
                                                        DispatchEntry* dispatchEntry,
                                                        KeyEntry& keyEntry, bool handled) {
diff --git a/services/inputflinger/dispatcher/InputDispatcher.h b/services/inputflinger/dispatcher/InputDispatcher.h
index df0be99..c7299e9 100644
--- a/services/inputflinger/dispatcher/InputDispatcher.h
+++ b/services/inputflinger/dispatcher/InputDispatcher.h
@@ -233,6 +233,8 @@
     // Finds the display ID of the gesture monitor identified by the provided token.
     std::optional<int32_t> findGestureMonitorDisplayByTokenLocked(const sp<IBinder>& token)
             REQUIRES(mLock);
+    // Find a monitor pid by the provided token.
+    std::optional<int32_t> findMonitorPidByTokenLocked(const sp<IBinder>& token) REQUIRES(mLock);
 
     // Input channels that will receive a copy of all input events sent to the provided display.
     std::unordered_map<int32_t, std::vector<Monitor>> mGlobalMonitorsByDisplay GUARDED_BY(mLock);
@@ -433,6 +435,34 @@
     void processNoFocusedWindowAnrLocked() REQUIRES(mLock);
 
     /**
+     * Tell policy about a window or a monitor that just became unresponsive. Starts ANR.
+     */
+    void processConnectionUnresponsiveLocked(const Connection& connection, std::string reason)
+            REQUIRES(mLock);
+    /**
+     * Tell policy about a window or a monitor that just became responsive.
+     */
+    void processConnectionResponsiveLocked(const Connection& connection) REQUIRES(mLock);
+
+    /**
+     * Post `doNotifyMonitorUnresponsiveLockedInterruptible` command.
+     */
+    void sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) REQUIRES(mLock);
+    /**
+     * Post `doNotifyWindowUnresponsiveLockedInterruptible` command.
+     */
+    void sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken, std::string reason)
+            REQUIRES(mLock);
+    /**
+     * Post `doNotifyMonitorResponsiveLockedInterruptible` command.
+     */
+    void sendMonitorResponsiveCommandLocked(int32_t pid) REQUIRES(mLock);
+    /**
+     * Post `doNotifyWindowResponsiveLockedInterruptible` command.
+     */
+    void sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) REQUIRES(mLock);
+
+    /**
      * This map will store the pending focus requests that cannot be currently processed. This can
      * happen if the window requested to be focused is not currently visible. Such a window might
      * become visible later, and these requests would be processed at that time.
@@ -577,7 +607,7 @@
                               int32_t displayId, std::string_view reason) REQUIRES(mLock);
     void notifyFocusChangedLocked(const sp<IBinder>& oldFocus, const sp<IBinder>& newFocus)
             REQUIRES(mLock);
-    void onAnrLocked(const Connection& connection) REQUIRES(mLock);
+    void onAnrLocked(const sp<Connection>& connection) REQUIRES(mLock);
     void onAnrLocked(std::shared_ptr<InputApplicationHandle> application) REQUIRES(mLock);
     void onUntrustedTouchLocked(const std::string& obscuringPackage) REQUIRES(mLock);
     void updateLastAnrStateLocked(const sp<InputWindowHandle>& window, const std::string& reason)
@@ -592,11 +622,13 @@
             REQUIRES(mLock);
     void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) REQUIRES(mLock);
     void doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) REQUIRES(mLock);
+    // ANR-related callbacks - start
     void doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) REQUIRES(mLock);
-    void doNotifyConnectionUnresponsiveLockedInterruptible(CommandEntry* commandEntry)
-            REQUIRES(mLock);
-    void doNotifyConnectionResponsiveLockedInterruptible(CommandEntry* commandEntry)
-            REQUIRES(mLock);
+    void doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) REQUIRES(mLock);
+    void doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) REQUIRES(mLock);
+    void doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) REQUIRES(mLock);
+    void doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) REQUIRES(mLock);
+    // ANR-related callbacks - end
     void doNotifySensorLockedInterruptible(CommandEntry* commandEntry) REQUIRES(mLock);
     void doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) REQUIRES(mLock);
     void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry)
diff --git a/services/inputflinger/dispatcher/include/InputDispatcherPolicyInterface.h b/services/inputflinger/dispatcher/include/InputDispatcherPolicyInterface.h
index d9ec020..b976129 100644
--- a/services/inputflinger/dispatcher/include/InputDispatcherPolicyInterface.h
+++ b/services/inputflinger/dispatcher/include/InputDispatcherPolicyInterface.h
@@ -50,20 +50,31 @@
     virtual void notifyNoFocusedWindowAnr(
             const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) = 0;
 
-    /* Notifies the system that a connection just became unresponsive. This indicates that ANR
-     * should be raised for this connection. The connection is identified via token.
+    /* Notifies the system that a window just became unresponsive. This indicates that ANR
+     * should be raised for this window. The window is identified via token.
      * The string reason contains information about the input event that we haven't received
      * a response for.
      */
-    virtual void notifyConnectionUnresponsive(const sp<IBinder>& token,
-                                              const std::string& reason) = 0;
+    virtual void notifyWindowUnresponsive(const sp<IBinder>& token, const std::string& reason) = 0;
+    /* Notifies the system that a monitor just became unresponsive. This indicates that ANR
+     * should be raised for this monitor. The monitor is identified via its pid.
+     * The string reason contains information about the input event that we haven't received
+     * a response for.
+     */
+    virtual void notifyMonitorUnresponsive(int32_t pid, const std::string& reason) = 0;
 
-    /* Notifies the system that a connection just became responsive. This is only called after the
-     * connection was first marked "unresponsive". This indicates that ANR dialog (if any) should
-     * no longer should be shown to the user. The connection is eligible to cause a new ANR in the
+    /* Notifies the system that a window just became responsive. This is only called after the
+     * window was first marked "unresponsive". This indicates that ANR dialog (if any) should
+     * no longer should be shown to the user. The window is eligible to cause a new ANR in the
      * future.
      */
-    virtual void notifyConnectionResponsive(const sp<IBinder>& token) = 0;
+    virtual void notifyWindowResponsive(const sp<IBinder>& token) = 0;
+    /* Notifies the system that a monitor just became responsive. This is only called after the
+     * monitor was first marked "unresponsive". This indicates that ANR dialog (if any) should
+     * no longer should be shown to the user. The monitor is eligible to cause a new ANR in the
+     * future.
+     */
+    virtual void notifyMonitorResponsive(int32_t pid) = 0;
 
     /* Notifies the system that an input channel is unrecoverably broken. */
     virtual void notifyInputChannelBroken(const sp<IBinder>& token) = 0;
diff --git a/services/inputflinger/tests/InputDispatcher_test.cpp b/services/inputflinger/tests/InputDispatcher_test.cpp
index 6d3500e..c7e05eb 100644
--- a/services/inputflinger/tests/InputDispatcher_test.cpp
+++ b/services/inputflinger/tests/InputDispatcher_test.cpp
@@ -140,27 +140,49 @@
         ASSERT_EQ(expectedApplication, application);
     }
 
-    void assertNotifyConnectionUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
-                                                     const sp<IBinder>& expectedConnectionToken) {
-        sp<IBinder> connectionToken = getUnresponsiveConnectionToken(timeout);
+    void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
+                                                 const sp<IBinder>& expectedConnectionToken) {
+        sp<IBinder> connectionToken = getUnresponsiveWindowToken(timeout);
         ASSERT_EQ(expectedConnectionToken, connectionToken);
     }
 
-    void assertNotifyConnectionResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
-        sp<IBinder> connectionToken = getResponsiveConnectionToken();
+    void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
+        sp<IBinder> connectionToken = getResponsiveWindowToken();
         ASSERT_EQ(expectedConnectionToken, connectionToken);
     }
 
-    sp<IBinder> getUnresponsiveConnectionToken(std::chrono::nanoseconds timeout) {
-        std::unique_lock lock(mLock);
-        android::base::ScopedLockAssertion assumeLocked(mLock);
-        return getAnrTokenLockedInterruptible(timeout, mAnrConnectionTokens, lock);
+    void assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout) {
+        int32_t pid = getUnresponsiveMonitorPid(timeout);
+        ASSERT_EQ(MONITOR_PID, pid);
     }
 
-    sp<IBinder> getResponsiveConnectionToken() {
+    void assertNotifyMonitorResponsiveWasCalled() {
+        int32_t pid = getResponsiveMonitorPid();
+        ASSERT_EQ(MONITOR_PID, pid);
+    }
+
+    sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
         std::unique_lock lock(mLock);
         android::base::ScopedLockAssertion assumeLocked(mLock);
-        return getAnrTokenLockedInterruptible(0s, mResponsiveConnectionTokens, lock);
+        return getAnrTokenLockedInterruptible(timeout, mAnrWindowTokens, lock);
+    }
+
+    sp<IBinder> getResponsiveWindowToken() {
+        std::unique_lock lock(mLock);
+        android::base::ScopedLockAssertion assumeLocked(mLock);
+        return getAnrTokenLockedInterruptible(0s, mResponsiveWindowTokens, lock);
+    }
+
+    int32_t getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout) {
+        std::unique_lock lock(mLock);
+        android::base::ScopedLockAssertion assumeLocked(mLock);
+        return getAnrTokenLockedInterruptible(timeout, mAnrMonitorPids, lock);
+    }
+
+    int32_t getResponsiveMonitorPid() {
+        std::unique_lock lock(mLock);
+        android::base::ScopedLockAssertion assumeLocked(mLock);
+        return getAnrTokenLockedInterruptible(0s, mResponsiveMonitorPids, lock);
     }
 
     // All three ANR-related callbacks behave the same way, so we use this generic function to wait
@@ -182,7 +204,7 @@
         const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
         if (storage.empty()) {
             ADD_FAILURE() << "Did not receive the ANR callback";
-            return nullptr;
+            return {};
         }
         // Ensure that the ANR didn't get raised too early. We can't be too strict here because
         // the dispatcher started counting before this function was called
@@ -201,10 +223,14 @@
     void assertNotifyAnrWasNotCalled() {
         std::scoped_lock lock(mLock);
         ASSERT_TRUE(mAnrApplications.empty());
-        ASSERT_TRUE(mAnrConnectionTokens.empty());
-        ASSERT_TRUE(mResponsiveConnectionTokens.empty())
+        ASSERT_TRUE(mAnrWindowTokens.empty());
+        ASSERT_TRUE(mAnrMonitorPids.empty());
+        ASSERT_TRUE(mResponsiveWindowTokens.empty())
                 << "ANR was not called, but please also consume the 'connection is responsive' "
                    "signal";
+        ASSERT_TRUE(mResponsiveMonitorPids.empty())
+                << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
+                   " signal";
     }
 
     void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
@@ -251,8 +277,10 @@
 
     // ANR handling
     std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
-    std::queue<sp<IBinder>> mAnrConnectionTokens GUARDED_BY(mLock);
-    std::queue<sp<IBinder>> mResponsiveConnectionTokens GUARDED_BY(mLock);
+    std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
+    std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
+    std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
+    std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
     std::condition_variable mNotifyAnr;
 
     void notifyConfigurationChanged(nsecs_t when) override {
@@ -260,16 +288,27 @@
         mConfigurationChangedTime = when;
     }
 
-    void notifyConnectionUnresponsive(const sp<IBinder>& connectionToken,
-                                      const std::string&) override {
+    void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
         std::scoped_lock lock(mLock);
-        mAnrConnectionTokens.push(connectionToken);
+        mAnrWindowTokens.push(connectionToken);
         mNotifyAnr.notify_all();
     }
 
-    void notifyConnectionResponsive(const sp<IBinder>& connectionToken) override {
+    void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
         std::scoped_lock lock(mLock);
-        mResponsiveConnectionTokens.push(connectionToken);
+        mAnrMonitorPids.push(pid);
+        mNotifyAnr.notify_all();
+    }
+
+    void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
+        std::scoped_lock lock(mLock);
+        mResponsiveWindowTokens.push(connectionToken);
+        mNotifyAnr.notify_all();
+    }
+
+    void notifyMonitorResponsive(int32_t pid) override {
+        std::scoped_lock lock(mLock);
+        mResponsiveMonitorPids.push(pid);
         mNotifyAnr.notify_all();
     }
 
@@ -1962,11 +2001,10 @@
     std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
     ASSERT_TRUE(consumeSeq);
 
-    mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(DISPATCHING_TIMEOUT,
-                                                             monitor.getToken());
+    mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
     monitor.finishEvent(*consumeSeq);
     ASSERT_TRUE(mDispatcher->waitForIdle());
-    mFakePolicy->assertNotifyConnectionResponsiveWasCalled(monitor.getToken());
+    mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
 }
 
 TEST_F(InputDispatcherTest, TestMoveEvent) {
@@ -3194,13 +3232,13 @@
     std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
     ASSERT_TRUE(sequenceNum);
     const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
-    mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
+    mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
 
     mWindow->finishEvent(*sequenceNum);
     mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
                           ADISPLAY_ID_DEFAULT, 0 /*flags*/);
     ASSERT_TRUE(mDispatcher->waitForIdle());
-    mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
+    mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
 }
 
 // Send a key to the app and have the app not respond right away.
@@ -3210,7 +3248,7 @@
     std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
     ASSERT_TRUE(sequenceNum);
     const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
-    mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
+    mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
     ASSERT_TRUE(mDispatcher->waitForIdle());
 }
 
@@ -3315,7 +3353,7 @@
     // We have now sent down and up. Let's consume first event and then ANR on the second.
     mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
     const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
-    mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
+    mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
 }
 
 // If an app is not responding to a key event, gesture monitors should continue to receive
@@ -3332,7 +3370,7 @@
 
     // Stuck on the ACTION_UP
     const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
-    mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
+    mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
 
     // New tap will go to the gesture monitor, but not to the window
     tapOnWindow();
@@ -3341,7 +3379,7 @@
 
     mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
     mDispatcher->waitForIdle();
-    mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
+    mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
     mWindow->assertNoEvents();
     monitor.assertNoEvents();
 }
@@ -3360,7 +3398,7 @@
     mWindow->consumeMotionDown();
     // Stuck on the ACTION_UP
     const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
-    mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
+    mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
 
     // New tap will go to the gesture monitor, but not to the window
     tapOnWindow();
@@ -3369,7 +3407,7 @@
 
     mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
     mDispatcher->waitForIdle();
-    mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
+    mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
     mWindow->assertNoEvents();
     monitor.assertNoEvents();
 }
@@ -3386,19 +3424,19 @@
     mWindow->consumeMotionDown();
     // Block on ACTION_UP
     const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
-    mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
+    mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
     mWindow->consumeMotionUp(); // Now the connection should be healthy again
     mDispatcher->waitForIdle();
-    mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
+    mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
     mWindow->assertNoEvents();
 
     tapOnWindow();
     mWindow->consumeMotionDown();
-    mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
+    mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
     mWindow->consumeMotionUp();
 
     mDispatcher->waitForIdle();
-    mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
+    mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
     mFakePolicy->assertNotifyAnrWasNotCalled();
     mWindow->assertNoEvents();
 }
@@ -3411,7 +3449,7 @@
                                WINDOW_LOCATION));
 
     const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
-    mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
+    mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
     std::this_thread::sleep_for(windowTimeout);
     // 'notifyConnectionUnresponsive' should only be called once per connection
     mFakePolicy->assertNotifyAnrWasNotCalled();
@@ -3421,7 +3459,7 @@
                           ADISPLAY_ID_DEFAULT, 0 /*flags*/);
     mWindow->assertNoEvents();
     mDispatcher->waitForIdle();
-    mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
+    mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
     mFakePolicy->assertNotifyAnrWasNotCalled();
 }
 
@@ -3589,7 +3627,7 @@
 
     const std::chrono::duration timeout =
             mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
-    mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
+    mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
     // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
     // sequence to make it consistent
     mFocusedWindow->consumeMotionCancel();
@@ -3600,7 +3638,7 @@
     mFocusedWindow->assertNoEvents();
     mUnfocusedWindow->assertNoEvents();
     ASSERT_TRUE(mDispatcher->waitForIdle());
-    mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mFocusedWindow->getToken());
+    mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
     mFakePolicy->assertNotifyAnrWasNotCalled();
 }
 
@@ -3614,8 +3652,8 @@
 
     tapOnFocusedWindow();
     // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
-    sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveConnectionToken(10ms);
-    sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveConnectionToken(0ms);
+    sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
+    sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
 
     // We don't know which window will ANR first. But both of them should happen eventually.
     ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
@@ -3630,8 +3668,8 @@
     mFocusedWindow->consumeMotionUp();
     mUnfocusedWindow->consumeMotionOutside();
 
-    sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveConnectionToken();
-    sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveConnectionToken();
+    sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
+    sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
 
     // Both applications should be marked as responsive, in any order
     ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
@@ -3655,7 +3693,7 @@
     ASSERT_TRUE(upEventSequenceNum);
     const std::chrono::duration timeout =
             mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
-    mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
+    mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
 
     // Tap once again
     // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
@@ -3676,7 +3714,7 @@
     // The second tap did not go to the focused window
     mFocusedWindow->assertNoEvents();
     // Since all events are finished, connection should be deemed healthy again
-    mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mFocusedWindow->getToken());
+    mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
     mFakePolicy->assertNotifyAnrWasNotCalled();
 }
 
@@ -3788,7 +3826,7 @@
 
     const std::chrono::duration timeout =
             mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
-    mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
+    mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
 
     mUnfocusedWindow->consumeMotionDown();
     mFocusedWindow->consumeMotionDown();
@@ -3807,7 +3845,7 @@
         ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
     }
     ASSERT_TRUE(mDispatcher->waitForIdle());
-    mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mFocusedWindow->getToken());
+    mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
 
     mUnfocusedWindow->assertNoEvents();
     mFocusedWindow->assertNoEvents();
diff --git a/services/surfaceflinger/CompositionEngine/tests/MockHWComposer.h b/services/surfaceflinger/CompositionEngine/tests/MockHWComposer.h
index e64a9f1..d0ba8fe 100644
--- a/services/surfaceflinger/CompositionEngine/tests/MockHWComposer.h
+++ b/services/surfaceflinger/CompositionEngine/tests/MockHWComposer.h
@@ -87,20 +87,17 @@
     MOCK_METHOD2(setVsyncEnabled, void(PhysicalDisplayId, hal::Vsync));
     MOCK_CONST_METHOD1(getRefreshTimestamp, nsecs_t(PhysicalDisplayId));
     MOCK_CONST_METHOD1(isConnected, bool(PhysicalDisplayId));
-    MOCK_CONST_METHOD1(
-            getConfigs,
-            std::vector<std::shared_ptr<const HWC2::Display::Config>>(PhysicalDisplayId));
-    MOCK_CONST_METHOD1(getActiveConfig,
-                       std::shared_ptr<const HWC2::Display::Config>(PhysicalDisplayId));
-    MOCK_CONST_METHOD1(getActiveConfigIndex, int(PhysicalDisplayId));
+    MOCK_CONST_METHOD1(getModes, DisplayModes(PhysicalDisplayId));
+    MOCK_CONST_METHOD1(getActiveMode, DisplayModePtr(PhysicalDisplayId));
     MOCK_CONST_METHOD1(getColorModes, std::vector<ui::ColorMode>(PhysicalDisplayId));
     MOCK_METHOD3(setActiveColorMode, status_t(PhysicalDisplayId, ui::ColorMode, ui::RenderIntent));
     MOCK_CONST_METHOD0(isUsingVrComposer, bool());
     MOCK_CONST_METHOD1(getDisplayConnectionType, DisplayConnectionType(PhysicalDisplayId));
     MOCK_CONST_METHOD1(isVsyncPeriodSwitchSupported, bool(PhysicalDisplayId));
     MOCK_CONST_METHOD1(getDisplayVsyncPeriod, nsecs_t(PhysicalDisplayId));
-    MOCK_METHOD4(setActiveConfigWithConstraints,
-                 status_t(PhysicalDisplayId, size_t, const hal::VsyncPeriodChangeConstraints&,
+    MOCK_METHOD4(setActiveModeWithConstraints,
+                 status_t(PhysicalDisplayId, HwcConfigIndexType,
+                          const hal::VsyncPeriodChangeConstraints&,
                           hal::VsyncPeriodChangeTimeline*));
     MOCK_METHOD2(setAutoLowLatencyMode, status_t(PhysicalDisplayId, bool));
     MOCK_METHOD2(getSupportedContentTypes,
diff --git a/services/surfaceflinger/DisplayDevice.cpp b/services/surfaceflinger/DisplayDevice.cpp
index cbc201f..8551365 100644
--- a/services/surfaceflinger/DisplayDevice.cpp
+++ b/services/surfaceflinger/DisplayDevice.cpp
@@ -210,7 +210,7 @@
     result.append("   ");
     StringAppendF(&result, "powerMode=%s (%d), ", to_string(mPowerMode).c_str(),
                   static_cast<int32_t>(mPowerMode));
-    StringAppendF(&result, "activeConfig=%d, ", mActiveConfig.value());
+    StringAppendF(&result, "activeConfig=%zu, ", mActiveConfig.value());
     StringAppendF(&result, "deviceProductInfo=");
     if (mDeviceProductInfo) {
         mDeviceProductInfo->dump(result);
diff --git a/services/surfaceflinger/DisplayHardware/DisplayMode.h b/services/surfaceflinger/DisplayHardware/DisplayMode.h
new file mode 100644
index 0000000..69fd00e
--- /dev/null
+++ b/services/surfaceflinger/DisplayHardware/DisplayMode.h
@@ -0,0 +1,131 @@
+/*
+ * 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 "DisplayHardware/Hal.h"
+#include "Scheduler/HwcStrongTypes.h"
+
+#include <android/configuration.h>
+#include <utils/Timers.h>
+
+#include <memory>
+#include <vector>
+
+namespace android {
+
+namespace hal = android::hardware::graphics::composer::hal;
+
+class DisplayMode;
+using DisplayModePtr = std::shared_ptr<const DisplayMode>;
+using DisplayModes = std::vector<DisplayModePtr>;
+
+class DisplayMode {
+public:
+    class Builder {
+    public:
+        explicit Builder(hal::HWConfigId id) : mDisplayMode(new DisplayMode(id)) {}
+
+        DisplayModePtr build() {
+            return std::const_pointer_cast<const DisplayMode>(std::move(mDisplayMode));
+        }
+
+        Builder& setId(HwcConfigIndexType id) {
+            mDisplayMode->mId = id;
+            return *this;
+        }
+
+        Builder& setWidth(int32_t width) {
+            mDisplayMode->mWidth = width;
+            return *this;
+        }
+
+        Builder& setHeight(int32_t height) {
+            mDisplayMode->mHeight = height;
+            return *this;
+        }
+
+        Builder& setVsyncPeriod(int32_t vsyncPeriod) {
+            mDisplayMode->mVsyncPeriod = vsyncPeriod;
+            return *this;
+        }
+
+        Builder& setDpiX(int32_t dpiX) {
+            if (dpiX == -1) {
+                mDisplayMode->mDpiX = getDefaultDensity();
+            } else {
+                mDisplayMode->mDpiX = dpiX / 1000.0f;
+            }
+            return *this;
+        }
+
+        Builder& setDpiY(int32_t dpiY) {
+            if (dpiY == -1) {
+                mDisplayMode->mDpiY = getDefaultDensity();
+            } else {
+                mDisplayMode->mDpiY = dpiY / 1000.0f;
+            }
+            return *this;
+        }
+
+        Builder& setConfigGroup(int32_t configGroup) {
+            mDisplayMode->mConfigGroup = configGroup;
+            return *this;
+        }
+
+    private:
+        float getDefaultDensity() {
+            // Default density is based on TVs: 1080p displays get XHIGH density, lower-
+            // resolution displays get TV density. Maybe eventually we'll need to update
+            // it for 4k displays, though hopefully those will just report accurate DPI
+            // information to begin with. This is also used for virtual displays and
+            // older HWC implementations, so be careful about orientation.
+
+            auto longDimension = std::max(mDisplayMode->mWidth, mDisplayMode->mHeight);
+            if (longDimension >= 1080) {
+                return ACONFIGURATION_DENSITY_XHIGH;
+            } else {
+                return ACONFIGURATION_DENSITY_TV;
+            }
+        }
+        std::shared_ptr<DisplayMode> mDisplayMode;
+    };
+
+    HwcConfigIndexType getId() const { return mId; }
+    hal::HWConfigId getHwcId() const { return mHwcId; }
+
+    int32_t getWidth() const { return mWidth; }
+    int32_t getHeight() const { return mHeight; }
+    nsecs_t getVsyncPeriod() const { return mVsyncPeriod; }
+    float getDpiX() const { return mDpiX; }
+    float getDpiY() const { return mDpiY; }
+    int32_t getConfigGroup() const { return mConfigGroup; }
+
+private:
+    explicit DisplayMode(hal::HWConfigId id) : mHwcId(id) {}
+
+    hal::HWConfigId mHwcId;
+    HwcConfigIndexType mId;
+
+    int32_t mWidth = -1;
+    int32_t mHeight = -1;
+    nsecs_t mVsyncPeriod = -1;
+    float mDpiX = -1;
+    float mDpiY = -1;
+    int32_t mConfigGroup = -1;
+};
+
+} // namespace android
\ No newline at end of file
diff --git a/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp b/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp
index 14b54cd..3e856bb 100644
--- a/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp
+++ b/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp
@@ -77,9 +77,8 @@
     mConsumer->setConsumerUsageBits(GRALLOC_USAGE_HW_FB |
                                        GRALLOC_USAGE_HW_RENDER |
                                        GRALLOC_USAGE_HW_COMPOSER);
-    const auto& activeConfig = mHwc.getActiveConfig(displayId);
-    ui::Size limitedSize =
-            limitFramebufferSize(activeConfig->getWidth(), activeConfig->getHeight());
+    const auto& activeMode = mHwc.getActiveMode(displayId);
+    ui::Size limitedSize = limitFramebufferSize(activeMode->getWidth(), activeMode->getHeight());
     mConsumer->setDefaultBufferSize(limitedSize.width, limitedSize.height);
     mConsumer->setMaxAcquiredBufferCount(
             SurfaceFlinger::maxFrameBufferAcquiredBuffers - 1);
diff --git a/services/surfaceflinger/DisplayHardware/HWC2.cpp b/services/surfaceflinger/DisplayHardware/HWC2.cpp
index 426092d..71a3276 100644
--- a/services/surfaceflinger/DisplayHardware/HWC2.cpp
+++ b/services/surfaceflinger/DisplayHardware/HWC2.cpp
@@ -68,33 +68,6 @@
 // Display methods
 Display::~Display() = default;
 
-Display::Config::Config(Display& display, HWConfigId id)
-      : mDisplay(display),
-        mId(id),
-        mWidth(-1),
-        mHeight(-1),
-        mVsyncPeriod(-1),
-        mDpiX(-1),
-        mDpiY(-1) {}
-
-Display::Config::Builder::Builder(Display& display, HWConfigId id)
-      : mConfig(new Config(display, id)) {}
-
-float Display::Config::Builder::getDefaultDensity() {
-    // Default density is based on TVs: 1080p displays get XHIGH density, lower-
-    // resolution displays get TV density. Maybe eventually we'll need to update
-    // it for 4k displays, though hopefully those will just report accurate DPI
-    // information to begin with. This is also used for virtual displays and
-    // older HWC implementations, so be careful about orientation.
-
-    auto longDimension = std::max(mConfig->mWidth, mConfig->mHeight);
-    if (longDimension >= 1080) {
-        return ACONFIGURATION_DENSITY_XHIGH;
-    } else {
-        return ACONFIGURATION_DENSITY_TV;
-    }
-}
-
 namespace impl {
 
 Display::Display(android::Hwc2::Composer& composer,
@@ -162,93 +135,12 @@
     return Error::NONE;
 }
 
-Error Display::getActiveConfig(
-        std::shared_ptr<const Display::Config>* outConfig) const
-{
-    ALOGV("[%" PRIu64 "] getActiveConfig", mId);
-    HWConfigId configId = 0;
-    auto intError = mComposer.getActiveConfig(mId, &configId);
-    auto error = static_cast<Error>(intError);
-
-    if (error != Error::NONE) {
-        ALOGE("Unable to get active config for mId:[%" PRIu64 "]", mId);
-        *outConfig = nullptr;
-        return error;
-    }
-
-    if (mConfigs.count(configId) != 0) {
-        *outConfig = mConfigs.at(configId);
-    } else {
-        ALOGE("[%" PRIu64 "] getActiveConfig returned unknown config %u", mId,
-                configId);
-        // Return no error, but the caller needs to check for a null pointer to
-        // detect this case
-        *outConfig = nullptr;
-    }
-
-    return Error::NONE;
-}
-
 bool Display::isVsyncPeriodSwitchSupported() const {
     ALOGV("[%" PRIu64 "] isVsyncPeriodSwitchSupported()", mId);
 
     return mComposer.isVsyncPeriodSwitchSupported();
 }
 
-Error Display::getDisplayVsyncPeriod(nsecs_t* outVsyncPeriod) const {
-    ALOGV("[%" PRIu64 "] getDisplayVsyncPeriod", mId);
-
-    Error error;
-
-    if (isVsyncPeriodSwitchSupported()) {
-        Hwc2::VsyncPeriodNanos vsyncPeriodNanos = 0;
-        auto intError = mComposer.getDisplayVsyncPeriod(mId, &vsyncPeriodNanos);
-        error = static_cast<Error>(intError);
-        *outVsyncPeriod = static_cast<nsecs_t>(vsyncPeriodNanos);
-    } else {
-        // Get the default vsync period
-        std::shared_ptr<const Display::Config> config;
-        error = getActiveConfig(&config);
-        if (error != Error::NONE) {
-            return error;
-        }
-        if (!config) {
-            // HWC has updated the display modes and hasn't notified us yet.
-            return Error::BAD_CONFIG;
-        }
-
-        *outVsyncPeriod = config->getVsyncPeriod();
-    }
-
-    return error;
-}
-
-Error Display::getActiveConfigIndex(int* outIndex) const {
-    ALOGV("[%" PRIu64 "] getActiveConfigIndex", mId);
-    HWConfigId configId = 0;
-    auto intError = mComposer.getActiveConfig(mId, &configId);
-    auto error = static_cast<Error>(intError);
-
-    if (error != Error::NONE) {
-        ALOGE("Unable to get active config for mId:[%" PRIu64 "]", mId);
-        *outIndex = -1;
-        return error;
-    }
-
-    auto pos = mConfigs.find(configId);
-    if (pos != mConfigs.end()) {
-        *outIndex = std::distance(mConfigs.begin(), pos);
-        ALOGV("[%" PRIu64 "] index = %d", mId, *outIndex);
-    } else {
-        ALOGE("[%" PRIu64 "] getActiveConfig returned unknown config %u", mId, configId);
-        // Return no error, but the caller needs to check for a negative index
-        // to detect this case
-        *outIndex = -1;
-    }
-
-    return Error::NONE;
-}
-
 Error Display::getChangedCompositionTypes(std::unordered_map<HWC2::Layer*, Composition>* outTypes) {
     std::vector<Hwc2::Layer> layerIds;
     std::vector<Hwc2::IComposerClient::Composition> types;
@@ -335,15 +227,6 @@
     return static_cast<Error>(intError);
 }
 
-std::vector<std::shared_ptr<const Display::Config>> Display::getConfigs() const
-{
-    std::vector<std::shared_ptr<const Config>> configs;
-    for (const auto& element : mConfigs) {
-        configs.emplace_back(element.second);
-    }
-    return configs;
-}
-
 Error Display::getName(std::string* outName) const
 {
     auto intError = mComposer.getDisplayName(mId, outName);
@@ -486,16 +369,10 @@
     return Error::NONE;
 }
 
-Error Display::setActiveConfigWithConstraints(
-        const std::shared_ptr<const HWC2::Display::Config>& config,
-        const VsyncPeriodChangeConstraints& constraints, VsyncPeriodChangeTimeline* outTimeline) {
+Error Display::setActiveConfigWithConstraints(hal::HWConfigId configId,
+                                              const VsyncPeriodChangeConstraints& constraints,
+                                              VsyncPeriodChangeTimeline* outTimeline) {
     ALOGV("[%" PRIu64 "] setActiveConfigWithConstraints", mId);
-    if (config->getDisplayId() != mId) {
-        ALOGE("setActiveConfigWithConstraints received config %u for the wrong display %" PRIu64
-              " (expected %" PRIu64 ")",
-              config->getId(), config->getDisplayId(), mId);
-        return Error::BAD_CONFIG;
-    }
 
     if (isVsyncPeriodSwitchSupported()) {
         Hwc2::IComposerClient::VsyncPeriodChangeConstraints hwc2Constraints;
@@ -503,9 +380,8 @@
         hwc2Constraints.seamlessRequired = constraints.seamlessRequired;
 
         Hwc2::VsyncPeriodChangeTimeline vsyncPeriodChangeTimeline = {};
-        auto intError =
-                mComposer.setActiveConfigWithConstraints(mId, config->getId(), hwc2Constraints,
-                                                         &vsyncPeriodChangeTimeline);
+        auto intError = mComposer.setActiveConfigWithConstraints(mId, configId, hwc2Constraints,
+                                                                 &vsyncPeriodChangeTimeline);
         outTimeline->newVsyncAppliedTimeNanos = vsyncPeriodChangeTimeline.newVsyncAppliedTimeNanos;
         outTimeline->refreshRequired = vsyncPeriodChangeTimeline.refreshRequired;
         outTimeline->refreshTimeNanos = vsyncPeriodChangeTimeline.refreshTimeNanos;
@@ -519,25 +395,13 @@
         ALOGE("setActiveConfigWithConstraints received constraints that can't be satisfied");
     }
 
-    auto intError_2_4 = mComposer.setActiveConfig(mId, config->getId());
+    auto intError_2_4 = mComposer.setActiveConfig(mId, configId);
     outTimeline->newVsyncAppliedTimeNanos = std::max(now, constraints.desiredTimeNanos);
     outTimeline->refreshRequired = true;
     outTimeline->refreshTimeNanos = now;
     return static_cast<Error>(intError_2_4);
 }
 
-Error Display::setActiveConfig(const std::shared_ptr<const Config>& config)
-{
-    if (config->getDisplayId() != mId) {
-        ALOGE("setActiveConfig received config %u for the wrong display %"
-                PRIu64 " (expected %" PRIu64 ")", config->getId(),
-                config->getDisplayId(), mId);
-        return Error::BAD_CONFIG;
-    }
-    auto intError = mComposer.setActiveConfig(mId, config->getId());
-    return static_cast<Error>(intError);
-}
-
 Error Display::setClientTarget(uint32_t slot, const sp<GraphicBuffer>& target,
         const sp<Fence>& acquireFence, Dataspace dataspace)
 {
@@ -681,58 +545,10 @@
 void Display::setConnected(bool connected) {
     if (!mIsConnected && connected) {
         mComposer.setClientTargetSlotCount(mId);
-        if (mType == DisplayType::PHYSICAL) {
-            loadConfigs();
-        }
     }
     mIsConnected = connected;
 }
 
-int32_t Display::getAttribute(HWConfigId configId, Attribute attribute) {
-    int32_t value = 0;
-    auto intError = mComposer.getDisplayAttribute(mId, configId, attribute, &value);
-    auto error = static_cast<Error>(intError);
-    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);
-        return -1;
-    }
-    return value;
-}
-
-void Display::loadConfig(HWConfigId configId) {
-    ALOGV("[%" PRIu64 "] loadConfig(%u)", mId, configId);
-
-    auto config = Config::Builder(*this, configId)
-                          .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));
-}
-
-void Display::loadConfigs()
-{
-    ALOGV("[%" PRIu64 "] loadConfigs", mId);
-
-    std::vector<HWConfigId> configIds;
-    auto intError = mComposer.getDisplayConfigs(mId, &configIds);
-    auto error = static_cast<Error>(intError);
-    if (error != Error::NONE) {
-        ALOGE("[%" PRIu64 "] getDisplayConfigs [2] failed: %s (%d)", mId,
-                to_string(error).c_str(), intError);
-        return;
-    }
-
-    for (auto configId : configIds) {
-        loadConfig(configId);
-    }
-}
-
 // Other Display methods
 
 HWC2::Layer* Display::getLayerById(HWLayerId id) const {
diff --git a/services/surfaceflinger/DisplayHardware/HWC2.h b/services/surfaceflinger/DisplayHardware/HWC2.h
index 89df84b..4c7f284 100644
--- a/services/surfaceflinger/DisplayHardware/HWC2.h
+++ b/services/surfaceflinger/DisplayHardware/HWC2.h
@@ -79,80 +79,6 @@
 public:
     virtual ~Display();
 
-    class Config {
-    public:
-        class Builder
-        {
-        public:
-            Builder(Display& display, hal::HWConfigId id);
-
-            std::shared_ptr<const Config> build() {
-                return std::const_pointer_cast<const Config>(
-                        std::move(mConfig));
-            }
-
-            Builder& setWidth(int32_t width) {
-                mConfig->mWidth = width;
-                return *this;
-            }
-            Builder& setHeight(int32_t height) {
-                mConfig->mHeight = height;
-                return *this;
-            }
-            Builder& setVsyncPeriod(int32_t vsyncPeriod) {
-                mConfig->mVsyncPeriod = vsyncPeriod;
-                return *this;
-            }
-            Builder& setDpiX(int32_t dpiX) {
-                if (dpiX == -1) {
-                    mConfig->mDpiX = getDefaultDensity();
-                } else {
-                    mConfig->mDpiX = dpiX / 1000.0f;
-                }
-                return *this;
-            }
-            Builder& setDpiY(int32_t dpiY) {
-                if (dpiY == -1) {
-                    mConfig->mDpiY = getDefaultDensity();
-                } else {
-                    mConfig->mDpiY = dpiY / 1000.0f;
-                }
-                return *this;
-            }
-            Builder& setConfigGroup(int32_t configGroup) {
-                mConfig->mConfigGroup = configGroup;
-                return *this;
-            }
-
-        private:
-            float getDefaultDensity();
-            std::shared_ptr<Config> mConfig;
-        };
-
-        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; }
-        nsecs_t getVsyncPeriod() const { return mVsyncPeriod; }
-        float getDpiX() const { return mDpiX; }
-        float getDpiY() const { return mDpiY; }
-        int32_t getConfigGroup() const { return mConfigGroup; }
-
-    private:
-        Config(Display& display, hal::HWConfigId id);
-
-        Display& mDisplay;
-        hal::HWConfigId mId;
-
-        int32_t mWidth;
-        int32_t mHeight;
-        nsecs_t mVsyncPeriod;
-        float mDpiX;
-        float mDpiY;
-        int32_t mConfigGroup;
-    };
-
     virtual hal::HWDisplayId getId() const = 0;
     virtual bool isConnected() const = 0;
     virtual void setConnected(bool connected) = 0; // For use by Device only
@@ -162,9 +88,6 @@
     [[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 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(
@@ -176,10 +99,6 @@
     [[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
-    [[clang::warn_unused_result]] virtual std::vector<std::shared_ptr<const Config>> getConfigs()
-            const = 0;
-
     [[clang::warn_unused_result]] virtual hal::Error getName(std::string* outName) const = 0;
     [[clang::warn_unused_result]] virtual hal::Error getRequests(
             hal::DisplayRequest* outDisplayRequests,
@@ -201,8 +120,6 @@
             std::unordered_map<Layer*, android::sp<android::Fence>>* outFences) const = 0;
     [[clang::warn_unused_result]] virtual hal::Error present(
             android::sp<android::Fence>* outPresentFence) = 0;
-    [[clang::warn_unused_result]] virtual hal::Error setActiveConfig(
-            const std::shared_ptr<const Config>& config) = 0;
     [[clang::warn_unused_result]] virtual hal::Error setClientTarget(
             uint32_t slot, const android::sp<android::GraphicBuffer>& target,
             const android::sp<android::Fence>& acquireFence, hal::Dataspace dataspace) = 0;
@@ -222,11 +139,8 @@
             android::sp<android::Fence>* outPresentFence, uint32_t* state) = 0;
     [[clang::warn_unused_result]] virtual std::future<hal::Error> setDisplayBrightness(
             float brightness) = 0;
-    [[clang::warn_unused_result]] virtual hal::Error getDisplayVsyncPeriod(
-            nsecs_t* outVsyncPeriod) const = 0;
     [[clang::warn_unused_result]] virtual hal::Error setActiveConfigWithConstraints(
-            const std::shared_ptr<const HWC2::Display::Config>& config,
-            const hal::VsyncPeriodChangeConstraints& constraints,
+            hal::HWConfigId configId, const hal::VsyncPeriodChangeConstraints& constraints,
             hal::VsyncPeriodChangeTimeline* outTimeline) = 0;
     [[clang::warn_unused_result]] virtual hal::Error setAutoLowLatencyMode(bool on) = 0;
     [[clang::warn_unused_result]] virtual hal::Error getSupportedContentTypes(
@@ -248,8 +162,6 @@
     hal::Error acceptChanges() override;
     hal::Error createLayer(Layer** outLayer) override;
     hal::Error destroyLayer(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;
@@ -259,9 +171,6 @@
                                 std::vector<hal::RenderIntent>* outRenderIntents) const override;
     hal::Error getDataspaceSaturationMatrix(hal::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;
-
     hal::Error getName(std::string* outName) const override;
     hal::Error getRequests(
             hal::DisplayRequest* outDisplayRequests,
@@ -279,7 +188,6 @@
     hal::Error getReleaseFences(
             std::unordered_map<Layer*, android::sp<android::Fence>>* outFences) 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;
@@ -294,11 +202,9 @@
                                  android::sp<android::Fence>* outPresentFence,
                                  uint32_t* state) override;
     std::future<hal::Error> setDisplayBrightness(float brightness) 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 setActiveConfigWithConstraints(hal::HWConfigId configId,
+                                              const hal::VsyncPeriodChangeConstraints& constraints,
+                                              hal::VsyncPeriodChangeTimeline* outTimeline) override;
     hal::Error setAutoLowLatencyMode(bool on) override;
     hal::Error getSupportedContentTypes(
             std::vector<hal::ContentType>* outSupportedContentTypes) const override;
@@ -315,9 +221,6 @@
     virtual bool isVsyncPeriodSwitchSupported() const override;
 
 private:
-    int32_t getAttribute(hal::HWConfigId, hal::Attribute);
-    void loadConfig(hal::HWConfigId);
-    void loadConfigs();
 
     // This may fail (and return a null pointer) if no layer with this ID exists
     // on this display
@@ -338,7 +241,6 @@
     bool mIsConnected = false;
 
     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<hal::DisplayCapability> mDisplayCapabilities;
diff --git a/services/surfaceflinger/DisplayHardware/HWComposer.cpp b/services/surfaceflinger/DisplayHardware/HWComposer.cpp
index 6f3987f..ca67935 100644
--- a/services/surfaceflinger/DisplayHardware/HWComposer.cpp
+++ b/services/surfaceflinger/DisplayHardware/HWComposer.cpp
@@ -281,6 +281,8 @@
 
 void HWComposer::allocatePhysicalDisplay(hal::HWDisplayId hwcDisplayId,
                                          PhysicalDisplayId displayId) {
+    mPhysicalDisplayIdMap[hwcDisplayId] = displayId;
+
     if (!mInternalHwcDisplayId) {
         mInternalHwcDisplayId = hwcDisplayId;
     } else if (mInternalHwcDisplayId != hwcDisplayId && !mExternalHwcDisplayId) {
@@ -293,8 +295,41 @@
                                                   hal::DisplayType::PHYSICAL);
     newDisplay->setConnected(true);
     displayData.hwcDisplay = std::move(newDisplay);
-    displayData.configs = displayData.hwcDisplay->getConfigs();
-    mPhysicalDisplayIdMap[hwcDisplayId] = displayId;
+    loadModes(displayData, hwcDisplayId);
+}
+
+int32_t HWComposer::getAttribute(hal::HWDisplayId hwcDisplayId, hal::HWConfigId configId,
+                                 hal::Attribute attribute) {
+    int32_t value = 0;
+    auto error = static_cast<hal::Error>(
+            mComposer->getDisplayAttribute(hwcDisplayId, configId, attribute, &value));
+
+    RETURN_IF_HWC_ERROR_FOR("getDisplayAttribute", error, *toPhysicalDisplayId(hwcDisplayId), -1);
+    return value;
+}
+
+void HWComposer::loadModes(DisplayData& displayData, hal::HWDisplayId hwcDisplayId) {
+    ALOGV("[HWC display %" PRIu64 "] %s", hwcDisplayId, __FUNCTION__);
+
+    std::vector<hal::HWConfigId> configIds;
+    auto error = static_cast<hal::Error>(mComposer->getDisplayConfigs(hwcDisplayId, &configIds));
+    RETURN_IF_HWC_ERROR_FOR("getDisplayConfigs", error, *toPhysicalDisplayId(hwcDisplayId));
+
+    displayData.modes.clear();
+    for (auto configId : configIds) {
+        auto mode = DisplayMode::Builder(configId)
+                            .setId(HwcConfigIndexType(displayData.modes.size()))
+                            .setWidth(getAttribute(hwcDisplayId, configId, hal::Attribute::WIDTH))
+                            .setHeight(getAttribute(hwcDisplayId, configId, hal::Attribute::HEIGHT))
+                            .setVsyncPeriod(getAttribute(hwcDisplayId, configId,
+                                                         hal::Attribute::VSYNC_PERIOD))
+                            .setDpiX(getAttribute(hwcDisplayId, configId, hal::Attribute::DPI_X))
+                            .setDpiY(getAttribute(hwcDisplayId, configId, hal::Attribute::DPI_Y))
+                            .setConfigGroup(getAttribute(hwcDisplayId, configId,
+                                                         hal::Attribute::CONFIG_GROUP))
+                            .build();
+        displayData.modes.push_back(std::move(mode));
+    }
 }
 
 HWC2::Layer* HWComposer::createLayer(HalDisplayId displayId) {
@@ -330,34 +365,38 @@
     return mDisplayData.at(displayId).hwcDisplay->isConnected();
 }
 
-std::vector<std::shared_ptr<const HWC2::Display::Config>> HWComposer::getConfigs(
-        PhysicalDisplayId displayId) const {
+DisplayModes HWComposer::getModes(PhysicalDisplayId displayId) const {
     RETURN_IF_INVALID_DISPLAY(displayId, {});
 
-    // We cache the configs when the DisplayData is created on hotplug. If the configs need to
+    // We cache the modes when the DisplayData is created on hotplug. If the modes need to
     // change HWC will send a hotplug event which will recreate displayData.
-    return mDisplayData.at(displayId).configs;
+    return mDisplayData.at(displayId).modes;
 }
 
-std::shared_ptr<const HWC2::Display::Config> HWComposer::getActiveConfig(
-        PhysicalDisplayId displayId) const {
+DisplayModePtr HWComposer::getActiveMode(PhysicalDisplayId displayId) const {
     RETURN_IF_INVALID_DISPLAY(displayId, nullptr);
 
-    std::shared_ptr<const HWC2::Display::Config> config;
-    auto error = mDisplayData.at(displayId).hwcDisplay->getActiveConfig(&config);
+    const auto hwcId = *fromPhysicalDisplayId(displayId);
+    ALOGV("[%" PRIu64 "] getActiveMode", hwcId);
+    hal::HWConfigId configId;
+    auto error = static_cast<hal::Error>(mComposer->getActiveConfig(hwcId, &configId));
+
+    const auto& modes = mDisplayData.at(displayId).modes;
     if (error == hal::Error::BAD_CONFIG) {
-        LOG_DISPLAY_ERROR(displayId, "No active config");
+        LOG_DISPLAY_ERROR(displayId, "No active mode");
         return nullptr;
     }
 
     RETURN_IF_HWC_ERROR(error, displayId, nullptr);
 
-    if (!config) {
-        LOG_DISPLAY_ERROR(displayId, "Unknown config");
+    const auto it = std::find_if(modes.begin(), modes.end(),
+                                 [configId](auto mode) { return mode->getHwcId() == configId; });
+    if (it == modes.end()) {
+        LOG_DISPLAY_ERROR(displayId, "Unknown mode");
         return nullptr;
     }
 
-    return config;
+    return *it;
 }
 
 // Composer 2.4
@@ -385,30 +424,24 @@
 nsecs_t HWComposer::getDisplayVsyncPeriod(PhysicalDisplayId displayId) const {
     RETURN_IF_INVALID_DISPLAY(displayId, 0);
 
-    nsecs_t vsyncPeriodNanos;
-    auto error = mDisplayData.at(displayId).hwcDisplay->getDisplayVsyncPeriod(&vsyncPeriodNanos);
-    RETURN_IF_HWC_ERROR(error, displayId, 0);
-    return vsyncPeriodNanos;
-}
-
-int HWComposer::getActiveConfigIndex(PhysicalDisplayId displayId) const {
-    RETURN_IF_INVALID_DISPLAY(displayId, -1);
-
-    int index;
-    auto error = mDisplayData.at(displayId).hwcDisplay->getActiveConfigIndex(&index);
-    if (error == hal::Error::BAD_CONFIG) {
-        LOG_DISPLAY_ERROR(displayId, "No active config");
-        return -1;
+    if (isVsyncPeriodSwitchSupported(displayId)) {
+        const auto hwcId = *fromPhysicalDisplayId(displayId);
+        Hwc2::VsyncPeriodNanos vsyncPeriodNanos = 0;
+        auto error =
+                static_cast<hal::Error>(mComposer->getDisplayVsyncPeriod(hwcId, &vsyncPeriodNanos));
+        RETURN_IF_HWC_ERROR(error, displayId, 0);
+        return static_cast<nsecs_t>(vsyncPeriodNanos);
     }
 
-    RETURN_IF_HWC_ERROR(error, displayId, -1);
+    // Get the default vsync period
+    auto mode = getActiveMode(displayId);
 
-    if (index < 0) {
-        LOG_DISPLAY_ERROR(displayId, "Unknown config");
-        return -1;
+    if (!mode) {
+        // HWC has updated the display modes and hasn't notified us yet.
+        RETURN_IF_HWC_ERROR(hal::Error::BAD_CONFIG, displayId, 0);
     }
 
-    return index;
+    return mode->getVsyncPeriod();
 }
 
 std::vector<ui::ColorMode> HWComposer::getColorModes(PhysicalDisplayId displayId) const {
@@ -640,21 +673,21 @@
     return NO_ERROR;
 }
 
-status_t HWComposer::setActiveConfigWithConstraints(
-        PhysicalDisplayId displayId, size_t configId,
+status_t HWComposer::setActiveModeWithConstraints(
+        PhysicalDisplayId displayId, HwcConfigIndexType modeId,
         const hal::VsyncPeriodChangeConstraints& constraints,
         hal::VsyncPeriodChangeTimeline* outTimeline) {
     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
 
     auto& displayData = mDisplayData[displayId];
-    if (configId >= displayData.configs.size()) {
-        LOG_DISPLAY_ERROR(displayId, ("Invalid config " + std::to_string(configId)).c_str());
+    if (modeId.value() >= displayData.modes.size()) {
+        LOG_DISPLAY_ERROR(displayId, ("Invalid mode " + std::to_string(modeId.value())).c_str());
         return BAD_INDEX;
     }
 
-    auto error =
-            displayData.hwcDisplay->setActiveConfigWithConstraints(displayData.configs[configId],
-                                                                   constraints, outTimeline);
+    const auto hwcConfigId = displayData.modes[modeId.value()]->getHwcId();
+    auto error = displayData.hwcDisplay->setActiveConfigWithConstraints(hwcConfigId, constraints,
+                                                                        outTimeline);
     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
     return NO_ERROR;
 }
diff --git a/services/surfaceflinger/DisplayHardware/HWComposer.h b/services/surfaceflinger/DisplayHardware/HWComposer.h
index 7e1da252..2b3d2d4 100644
--- a/services/surfaceflinger/DisplayHardware/HWComposer.h
+++ b/services/surfaceflinger/DisplayHardware/HWComposer.h
@@ -41,6 +41,7 @@
 
 #include "DisplayIdGenerator.h"
 #include "DisplayIdentification.h"
+#include "DisplayMode.h"
 #include "HWC2.h"
 #include "Hal.h"
 
@@ -184,12 +185,9 @@
     virtual nsecs_t getRefreshTimestamp(PhysicalDisplayId) const = 0;
     virtual bool isConnected(PhysicalDisplayId) const = 0;
 
-    virtual std::vector<std::shared_ptr<const HWC2::Display::Config>> getConfigs(
-            PhysicalDisplayId) const = 0;
+    virtual DisplayModes getModes(PhysicalDisplayId) const = 0;
 
-    virtual std::shared_ptr<const HWC2::Display::Config> getActiveConfig(
-            PhysicalDisplayId) const = 0;
-    virtual int getActiveConfigIndex(PhysicalDisplayId) const = 0;
+    virtual DisplayModePtr getActiveMode(PhysicalDisplayId) const = 0;
 
     virtual std::vector<ui::ColorMode> getColorModes(PhysicalDisplayId) const = 0;
 
@@ -200,9 +198,9 @@
     virtual DisplayConnectionType getDisplayConnectionType(PhysicalDisplayId) const = 0;
     virtual bool isVsyncPeriodSwitchSupported(PhysicalDisplayId) const = 0;
     virtual nsecs_t getDisplayVsyncPeriod(PhysicalDisplayId) const = 0;
-    virtual status_t setActiveConfigWithConstraints(
-            PhysicalDisplayId, size_t configId, const hal::VsyncPeriodChangeConstraints&,
-            hal::VsyncPeriodChangeTimeline* outTimeline) = 0;
+    virtual status_t setActiveModeWithConstraints(PhysicalDisplayId, HwcConfigIndexType,
+                                                  const hal::VsyncPeriodChangeConstraints&,
+                                                  hal::VsyncPeriodChangeTimeline* outTimeline) = 0;
     virtual status_t setAutoLowLatencyMode(PhysicalDisplayId, bool on) = 0;
     virtual status_t getSupportedContentTypes(
             PhysicalDisplayId, std::vector<hal::ContentType>* outSupportedContentTypes) = 0;
@@ -319,11 +317,9 @@
     nsecs_t getRefreshTimestamp(PhysicalDisplayId) const override;
     bool isConnected(PhysicalDisplayId) const override;
 
-    std::vector<std::shared_ptr<const HWC2::Display::Config>> getConfigs(
-            PhysicalDisplayId) const override;
+    DisplayModes getModes(PhysicalDisplayId) const override;
 
-    std::shared_ptr<const HWC2::Display::Config> getActiveConfig(PhysicalDisplayId) const override;
-    int getActiveConfigIndex(PhysicalDisplayId) const override;
+    DisplayModePtr getActiveMode(PhysicalDisplayId) const override;
 
     std::vector<ui::ColorMode> getColorModes(PhysicalDisplayId) const override;
 
@@ -332,10 +328,10 @@
     // Composer 2.4
     DisplayConnectionType getDisplayConnectionType(PhysicalDisplayId) const override;
     bool isVsyncPeriodSwitchSupported(PhysicalDisplayId) const override;
-    nsecs_t getDisplayVsyncPeriod(PhysicalDisplayId) const override;
-    status_t setActiveConfigWithConstraints(PhysicalDisplayId, size_t configId,
-                                            const hal::VsyncPeriodChangeConstraints&,
-                                            hal::VsyncPeriodChangeTimeline* outTimeline) override;
+    nsecs_t getDisplayVsyncPeriod(PhysicalDisplayId displayId) const override;
+    status_t setActiveModeWithConstraints(PhysicalDisplayId, HwcConfigIndexType,
+                                          const hal::VsyncPeriodChangeConstraints&,
+                                          hal::VsyncPeriodChangeTimeline* outTimeline) override;
     status_t setAutoLowLatencyMode(PhysicalDisplayId, bool) override;
     status_t getSupportedContentTypes(PhysicalDisplayId, std::vector<hal::ContentType>*) override;
     status_t setContentType(PhysicalDisplayId, hal::ContentType) override;
@@ -362,14 +358,6 @@
     // For unit tests
     friend TestableSurfaceFlinger;
 
-    std::optional<DisplayIdentificationInfo> onHotplugConnect(hal::HWDisplayId);
-    std::optional<DisplayIdentificationInfo> onHotplugDisconnect(hal::HWDisplayId);
-    bool shouldIgnoreHotplugConnect(hal::HWDisplayId, bool hasDisplayIdentificationData) const;
-
-    void loadCapabilities();
-    void loadLayerMetadataSupport();
-    uint32_t getMaxVirtualDisplayCount() const;
-
     struct DisplayData {
         bool isVirtual = false;
         std::unique_ptr<HWC2::Display> hwcDisplay;
@@ -377,7 +365,7 @@
         std::unordered_map<HWC2::Layer*, sp<Fence>> releaseFences;
         buffer_handle_t outbufHandle = nullptr;
         sp<Fence> outbufAcquireFence = Fence::NO_FENCE;
-        std::vector<std::shared_ptr<const HWC2::Display::Config>> configs;
+        DisplayModes modes;
 
         bool validateWasSkipped;
         hal::Error presentError;
@@ -391,6 +379,18 @@
         nsecs_t lastHwVsync GUARDED_BY(lastHwVsyncLock) = 0;
     };
 
+    std::optional<DisplayIdentificationInfo> onHotplugConnect(hal::HWDisplayId);
+    std::optional<DisplayIdentificationInfo> onHotplugDisconnect(hal::HWDisplayId);
+    bool shouldIgnoreHotplugConnect(hal::HWDisplayId, bool hasDisplayIdentificationData) const;
+
+    int32_t getAttribute(hal::HWDisplayId hwcDisplayId, hal::HWConfigId configId,
+                         hal::Attribute attribute);
+    void loadModes(DisplayData& displayData, hal::HWDisplayId hwcDisplayId);
+
+    void loadCapabilities();
+    void loadLayerMetadataSupport();
+    uint32_t getMaxVirtualDisplayCount() const;
+
     std::unordered_map<HalDisplayId, DisplayData> mDisplayData;
 
     std::unique_ptr<android::Hwc2::Composer> mComposer;
diff --git a/services/surfaceflinger/FrameTimeline/FrameTimeline.cpp b/services/surfaceflinger/FrameTimeline/FrameTimeline.cpp
index a8fef04..c994434 100644
--- a/services/surfaceflinger/FrameTimeline/FrameTimeline.cpp
+++ b/services/surfaceflinger/FrameTimeline/FrameTimeline.cpp
@@ -239,11 +239,16 @@
     return minTime;
 }
 
+int64_t TraceCookieCounter::getCookieForTracing() {
+    return ++mTraceCookie;
+}
+
 SurfaceFrame::SurfaceFrame(int64_t token, pid_t ownerPid, uid_t ownerUid, std::string layerName,
                            std::string debugName, PredictionState predictionState,
                            frametimeline::TimelineItem&& predictions,
                            std::shared_ptr<TimeStats> timeStats,
-                           JankClassificationThresholds thresholds)
+                           JankClassificationThresholds thresholds,
+                           TraceCookieCounter* traceCookieCounter)
       : mToken(token),
         mOwnerPid(ownerPid),
         mOwnerUid(ownerUid),
@@ -254,7 +259,8 @@
         mPredictions(predictions),
         mActuals({0, 0, 0}),
         mTimeStats(timeStats),
-        mJankClassificationThresholds(thresholds) {}
+        mJankClassificationThresholds(thresholds),
+        mTraceCookieCounter(*traceCookieCounter) {}
 
 void SurfaceFrame::setActualStartTime(nsecs_t actualStartTime) {
     std::lock_guard<std::mutex> lock(mMutex);
@@ -443,7 +449,7 @@
 
 void SurfaceFrame::trace(int64_t displayFrameToken) {
     using FrameTimelineDataSource = impl::FrameTimeline::FrameTimelineDataSource;
-    FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
+    {
         std::lock_guard<std::mutex> lock(mMutex);
         if (mToken == ISurfaceComposer::INVALID_VSYNC_ID) {
             ALOGD("Cannot trace SurfaceFrame - %s with invalid token", mLayerName.c_str());
@@ -453,36 +459,83 @@
                   mLayerName.c_str());
             return;
         }
+    }
+
+    int64_t expectedTimelineCookie = mTraceCookieCounter.getCookieForTracing();
+    // Expected timeline start
+    FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
+        std::lock_guard<std::mutex> lock(mMutex);
         auto packet = ctx.NewTracePacket();
         packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
-        packet->set_timestamp(static_cast<uint64_t>(systemTime()));
+        packet->set_timestamp(static_cast<uint64_t>(mPredictions.startTime));
 
         auto* event = packet->set_frame_timeline_event();
-        auto* surfaceFrameEvent = event->set_surface_frame();
+        auto* expectedSurfaceFrameStartEvent = event->set_expected_surface_frame_start();
 
-        surfaceFrameEvent->set_token(mToken);
-        surfaceFrameEvent->set_display_frame_token(displayFrameToken);
+        expectedSurfaceFrameStartEvent->set_cookie(expectedTimelineCookie);
+
+        expectedSurfaceFrameStartEvent->set_token(mToken);
+        expectedSurfaceFrameStartEvent->set_display_frame_token(displayFrameToken);
+
+        expectedSurfaceFrameStartEvent->set_pid(mOwnerPid);
+        expectedSurfaceFrameStartEvent->set_layer_name(mDebugName);
+    });
+    // Expected timeline end
+    FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
+        std::lock_guard<std::mutex> lock(mMutex);
+        auto packet = ctx.NewTracePacket();
+        packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
+        packet->set_timestamp(static_cast<uint64_t>(mPredictions.endTime));
+
+        auto* event = packet->set_frame_timeline_event();
+        auto* expectedSurfaceFrameEndEvent = event->set_frame_end();
+
+        expectedSurfaceFrameEndEvent->set_cookie(expectedTimelineCookie);
+    });
+
+    int64_t actualTimelineCookie = mTraceCookieCounter.getCookieForTracing();
+    // Actual timeline start
+    FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
+        std::lock_guard<std::mutex> lock(mMutex);
+        auto packet = ctx.NewTracePacket();
+        packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
+        // Actual start time is not yet available, so use expected start instead
+        packet->set_timestamp(static_cast<uint64_t>(mPredictions.startTime));
+
+        auto* event = packet->set_frame_timeline_event();
+        auto* actualSurfaceFrameStartEvent = event->set_actual_surface_frame_start();
+
+        actualSurfaceFrameStartEvent->set_cookie(actualTimelineCookie);
+
+        actualSurfaceFrameStartEvent->set_token(mToken);
+        actualSurfaceFrameStartEvent->set_display_frame_token(displayFrameToken);
+
+        actualSurfaceFrameStartEvent->set_pid(mOwnerPid);
+        actualSurfaceFrameStartEvent->set_layer_name(mDebugName);
 
         if (mPresentState == PresentState::Dropped) {
-            surfaceFrameEvent->set_present_type(FrameTimelineEvent::PRESENT_DROPPED);
+            actualSurfaceFrameStartEvent->set_present_type(FrameTimelineEvent::PRESENT_DROPPED);
         } else if (mPresentState == PresentState::Unknown) {
-            surfaceFrameEvent->set_present_type(FrameTimelineEvent::PRESENT_UNSPECIFIED);
+            actualSurfaceFrameStartEvent->set_present_type(FrameTimelineEvent::PRESENT_UNSPECIFIED);
         } else {
-            surfaceFrameEvent->set_present_type(toProto(mFramePresentMetadata));
+            actualSurfaceFrameStartEvent->set_present_type(toProto(mFramePresentMetadata));
         }
-        surfaceFrameEvent->set_on_time_finish(mFrameReadyMetadata ==
-                                              FrameReadyMetadata::OnTimeFinish);
-        surfaceFrameEvent->set_gpu_composition(mGpuComposition);
-        surfaceFrameEvent->set_jank_type(jankTypeBitmaskToProto(mJankType));
+        actualSurfaceFrameStartEvent->set_on_time_finish(mFrameReadyMetadata ==
+                                                         FrameReadyMetadata::OnTimeFinish);
+        actualSurfaceFrameStartEvent->set_gpu_composition(mGpuComposition);
+        actualSurfaceFrameStartEvent->set_jank_type(jankTypeBitmaskToProto(mJankType));
+    });
+    // Actual timeline end
+    FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
+        std::lock_guard<std::mutex> lock(mMutex);
+        auto packet = ctx.NewTracePacket();
+        packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
+        packet->set_timestamp(static_cast<uint64_t>(mActuals.endTime));
 
-        surfaceFrameEvent->set_expected_start_ns(mPredictions.startTime);
-        surfaceFrameEvent->set_expected_end_ns(mPredictions.endTime);
+        auto* event = packet->set_frame_timeline_event();
+        auto* actualSurfaceFrameEndEvent = event->set_frame_end();
 
-        surfaceFrameEvent->set_actual_start_ns(mActuals.startTime);
-        surfaceFrameEvent->set_actual_end_ns(mActuals.endTime);
-
-        surfaceFrameEvent->set_layer_name(mDebugName);
-        surfaceFrameEvent->set_pid(mOwnerPid);
+        actualSurfaceFrameEndEvent->set_cookie(actualTimelineCookie);
     });
 }
 
@@ -520,11 +573,13 @@
 
 FrameTimeline::FrameTimeline(std::shared_ptr<TimeStats> timeStats, pid_t surfaceFlingerPid,
                              JankClassificationThresholds thresholds)
-      : mCurrentDisplayFrame(std::make_shared<DisplayFrame>(timeStats, thresholds)),
-        mMaxDisplayFrames(kDefaultMaxDisplayFrames),
+      : mMaxDisplayFrames(kDefaultMaxDisplayFrames),
         mTimeStats(std::move(timeStats)),
         mSurfaceFlingerPid(surfaceFlingerPid),
-        mJankClassificationThresholds(thresholds) {}
+        mJankClassificationThresholds(thresholds) {
+    mCurrentDisplayFrame =
+            std::make_shared<DisplayFrame>(mTimeStats, thresholds, &mTraceCookieCounter);
+}
 
 void FrameTimeline::onBootFinished() {
     perfetto::TracingInitArgs args;
@@ -547,27 +602,29 @@
         return std::make_shared<SurfaceFrame>(ISurfaceComposer::INVALID_VSYNC_ID, ownerPid,
                                               ownerUid, std::move(layerName), std::move(debugName),
                                               PredictionState::None, TimelineItem(), mTimeStats,
-                                              mJankClassificationThresholds);
+                                              mJankClassificationThresholds, &mTraceCookieCounter);
     }
     std::optional<TimelineItem> predictions = mTokenManager.getPredictionsForToken(*token);
     if (predictions) {
         return std::make_shared<SurfaceFrame>(*token, ownerPid, ownerUid, std::move(layerName),
                                               std::move(debugName), PredictionState::Valid,
                                               std::move(*predictions), mTimeStats,
-                                              mJankClassificationThresholds);
+                                              mJankClassificationThresholds, &mTraceCookieCounter);
     }
     return std::make_shared<SurfaceFrame>(*token, ownerPid, ownerUid, std::move(layerName),
                                           std::move(debugName), PredictionState::Expired,
-                                          TimelineItem(), mTimeStats,
-                                          mJankClassificationThresholds);
+                                          TimelineItem(), mTimeStats, mJankClassificationThresholds,
+                                          &mTraceCookieCounter);
 }
 
 FrameTimeline::DisplayFrame::DisplayFrame(std::shared_ptr<TimeStats> timeStats,
-                                          JankClassificationThresholds thresholds)
+                                          JankClassificationThresholds thresholds,
+                                          TraceCookieCounter* traceCookieCounter)
       : mSurfaceFlingerPredictions(TimelineItem()),
         mSurfaceFlingerActuals(TimelineItem()),
         mTimeStats(timeStats),
-        mJankClassificationThresholds(thresholds) {
+        mJankClassificationThresholds(thresholds),
+        mTraceCookieCounter(*traceCookieCounter) {
     mSurfaceFrames.reserve(kNumSurfaceFramesInitial);
 }
 
@@ -725,32 +782,69 @@
 }
 
 void FrameTimeline::DisplayFrame::trace(pid_t surfaceFlingerPid) const {
+    if (mToken == ISurfaceComposer::INVALID_VSYNC_ID) {
+        ALOGD("Cannot trace DisplayFrame with invalid token");
+        return;
+    }
+
+    int64_t expectedTimelineCookie = mTraceCookieCounter.getCookieForTracing();
+    // Expected timeline start
     FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
-        if (mToken == ISurfaceComposer::INVALID_VSYNC_ID) {
-            ALOGD("Cannot trace DisplayFrame with invalid token");
-            return;
-        }
         auto packet = ctx.NewTracePacket();
         packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
-        packet->set_timestamp(static_cast<uint64_t>(systemTime()));
+        packet->set_timestamp(static_cast<uint64_t>(mSurfaceFlingerPredictions.startTime));
 
         auto* event = packet->set_frame_timeline_event();
-        auto* displayFrameEvent = event->set_display_frame();
+        auto* expectedDisplayFrameStartEvent = event->set_expected_display_frame_start();
 
-        displayFrameEvent->set_token(mToken);
-        displayFrameEvent->set_present_type(toProto(mFramePresentMetadata));
-        displayFrameEvent->set_on_time_finish(mFrameReadyMetadata ==
-                                              FrameReadyMetadata::OnTimeFinish);
-        displayFrameEvent->set_gpu_composition(mGpuComposition);
-        displayFrameEvent->set_jank_type(jankTypeBitmaskToProto(mJankType));
+        expectedDisplayFrameStartEvent->set_cookie(expectedTimelineCookie);
 
-        displayFrameEvent->set_expected_start_ns(mSurfaceFlingerPredictions.startTime);
-        displayFrameEvent->set_expected_end_ns(mSurfaceFlingerPredictions.endTime);
+        expectedDisplayFrameStartEvent->set_token(mToken);
+        expectedDisplayFrameStartEvent->set_pid(surfaceFlingerPid);
+    });
+    // Expected timeline end
+    FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
+        auto packet = ctx.NewTracePacket();
+        packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
+        packet->set_timestamp(static_cast<uint64_t>(mSurfaceFlingerPredictions.endTime));
 
-        displayFrameEvent->set_actual_start_ns(mSurfaceFlingerActuals.startTime);
-        displayFrameEvent->set_actual_end_ns(mSurfaceFlingerActuals.endTime);
+        auto* event = packet->set_frame_timeline_event();
+        auto* expectedDisplayFrameEndEvent = event->set_frame_end();
 
-        displayFrameEvent->set_pid(surfaceFlingerPid);
+        expectedDisplayFrameEndEvent->set_cookie(expectedTimelineCookie);
+    });
+
+    int64_t actualTimelineCookie = mTraceCookieCounter.getCookieForTracing();
+    // Expected timeline start
+    FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
+        auto packet = ctx.NewTracePacket();
+        packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
+        packet->set_timestamp(static_cast<uint64_t>(mSurfaceFlingerActuals.startTime));
+
+        auto* event = packet->set_frame_timeline_event();
+        auto* actualDisplayFrameStartEvent = event->set_actual_display_frame_start();
+
+        actualDisplayFrameStartEvent->set_cookie(actualTimelineCookie);
+
+        actualDisplayFrameStartEvent->set_token(mToken);
+        actualDisplayFrameStartEvent->set_pid(surfaceFlingerPid);
+
+        actualDisplayFrameStartEvent->set_present_type(toProto(mFramePresentMetadata));
+        actualDisplayFrameStartEvent->set_on_time_finish(mFrameReadyMetadata ==
+                                                         FrameReadyMetadata::OnTimeFinish);
+        actualDisplayFrameStartEvent->set_gpu_composition(mGpuComposition);
+        actualDisplayFrameStartEvent->set_jank_type(jankTypeBitmaskToProto(mJankType));
+    });
+    // Expected timeline end
+    FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
+        auto packet = ctx.NewTracePacket();
+        packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
+        packet->set_timestamp(static_cast<uint64_t>(mSurfaceFlingerActuals.endTime));
+
+        auto* event = packet->set_frame_timeline_event();
+        auto* actualDisplayFrameEndEvent = event->set_frame_end();
+
+        actualDisplayFrameEndEvent->set_cookie(actualTimelineCookie);
     });
 
     for (auto& surfaceFrame : mSurfaceFrames) {
@@ -786,8 +880,8 @@
     }
     mDisplayFrames.push_back(mCurrentDisplayFrame);
     mCurrentDisplayFrame.reset();
-    mCurrentDisplayFrame =
-            std::make_shared<DisplayFrame>(mTimeStats, mJankClassificationThresholds);
+    mCurrentDisplayFrame = std::make_shared<DisplayFrame>(mTimeStats, mJankClassificationThresholds,
+                                                          &mTraceCookieCounter);
 }
 
 nsecs_t FrameTimeline::DisplayFrame::getBaseTime() const {
diff --git a/services/surfaceflinger/FrameTimeline/FrameTimeline.h b/services/surfaceflinger/FrameTimeline/FrameTimeline.h
index f5239aa..ed38cc6 100644
--- a/services/surfaceflinger/FrameTimeline/FrameTimeline.h
+++ b/services/surfaceflinger/FrameTimeline/FrameTimeline.h
@@ -127,6 +127,23 @@
     None,    // Predictions are either not present or didn't come from TokenManager
 };
 
+/*
+ * Trace cookie is used to send start and end timestamps of <Surface/Display>Frames separately
+ * without needing to resend all the other information. We send all info to perfetto, along with a
+ * new cookie, in the start of a frame. For the corresponding end, we just send the same cookie.
+ * This helps in reducing the amount of data emitted by the producer.
+ */
+class TraceCookieCounter {
+public:
+    int64_t getCookieForTracing();
+
+private:
+    // Friend class for testing
+    friend class android::frametimeline::FrameTimelineTest;
+
+    std::atomic<int64_t> mTraceCookie = 0;
+};
+
 class SurfaceFrame {
 public:
     enum class PresentState {
@@ -139,7 +156,8 @@
     // TokenManager), Thresholds and TimeStats pointer.
     SurfaceFrame(int64_t token, pid_t ownerPid, uid_t ownerUid, std::string layerName,
                  std::string debugName, PredictionState predictionState, TimelineItem&& predictions,
-                 std::shared_ptr<TimeStats> timeStats, JankClassificationThresholds thresholds);
+                 std::shared_ptr<TimeStats> timeStats, JankClassificationThresholds thresholds,
+                 TraceCookieCounter* traceCookieCounter);
     ~SurfaceFrame() = default;
 
     // Returns std::nullopt if the frame hasn't been classified yet.
@@ -205,6 +223,9 @@
     // for BufferStuffing where the current buffer is expected to be ready but the previous buffer
     // was latched instead.
     nsecs_t mLastLatchTime GUARDED_BY(mMutex) = 0;
+    // TraceCookieCounter is used to obtain the cookie for sendig trace packets to perfetto. Using a
+    // reference here because the counter is owned by FrameTimeline, which outlives SurfaceFrame.
+    TraceCookieCounter& mTraceCookieCounter;
 };
 
 /*
@@ -291,7 +312,8 @@
      */
     class DisplayFrame {
     public:
-        DisplayFrame(std::shared_ptr<TimeStats> timeStats, JankClassificationThresholds thresholds);
+        DisplayFrame(std::shared_ptr<TimeStats> timeStats, JankClassificationThresholds thresholds,
+                     TraceCookieCounter* traceCookieCounter);
         virtual ~DisplayFrame() = default;
         // Dumpsys interface - dumps only if the DisplayFrame itself is janky or is at least one
         // SurfaceFrame is janky.
@@ -360,6 +382,10 @@
         // The refresh rate (vsync period) in nanoseconds as seen by SF during this DisplayFrame's
         // timeline
         nsecs_t mVsyncPeriod = 0;
+        // TraceCookieCounter is used to obtain the cookie for sendig trace packets to perfetto.
+        // Using a reference here because the counter is owned by FrameTimeline, which outlives
+        // DisplayFrame.
+        TraceCookieCounter& mTraceCookieCounter;
     };
 
     FrameTimeline(std::shared_ptr<TimeStats> timeStats, pid_t surfaceFlingerPid,
@@ -402,6 +428,7 @@
             mPendingPresentFences GUARDED_BY(mMutex);
     std::shared_ptr<DisplayFrame> mCurrentDisplayFrame GUARDED_BY(mMutex);
     TokenManager mTokenManager;
+    TraceCookieCounter mTraceCookieCounter;
     mutable std::mutex mMutex;
     uint32_t mMaxDisplayFrames;
     std::shared_ptr<TimeStats> mTimeStats;
diff --git a/services/surfaceflinger/RefreshRateOverlay.cpp b/services/surfaceflinger/RefreshRateOverlay.cpp
index 32110e9..9230e72 100644
--- a/services/surfaceflinger/RefreshRateOverlay.cpp
+++ b/services/surfaceflinger/RefreshRateOverlay.cpp
@@ -233,8 +233,8 @@
     mFlinger.mTransactionFlags.fetch_or(eTransactionMask);
 }
 
-void RefreshRateOverlay::changeRefreshRate(const RefreshRate& refreshRate) {
-    mCurrentFps = refreshRate.getFps().getIntValue();
+void RefreshRateOverlay::changeRefreshRate(const Fps& fps) {
+    mCurrentFps = fps.getIntValue();
     auto buffer = getOrCreateBuffers(*mCurrentFps)[mFrame];
     mLayer->setBuffer(buffer, Fence::NO_FENCE, 0, 0, true, {},
                       mLayer->getHeadFrameNumber(-1 /* expectedPresentTime */),
@@ -258,8 +258,9 @@
 
 void RefreshRateOverlay::reset() {
     mBufferCache.clear();
-    mLowFps = mFlinger.mRefreshRateConfigs->getMinRefreshRate().getFps().getIntValue();
-    mHighFps = mFlinger.mRefreshRateConfigs->getMaxRefreshRate().getFps().getIntValue();
+    const auto range = mFlinger.mRefreshRateConfigs->getSupportedRefreshRateRange();
+    mLowFps = range.min.getIntValue();
+    mHighFps = range.max.getIntValue();
 }
 
 } // namespace android
diff --git a/services/surfaceflinger/RefreshRateOverlay.h b/services/surfaceflinger/RefreshRateOverlay.h
index 4ca1337..c16cfa0 100644
--- a/services/surfaceflinger/RefreshRateOverlay.h
+++ b/services/surfaceflinger/RefreshRateOverlay.h
@@ -23,7 +23,7 @@
 #include <ui/Size.h>
 #include <utils/StrongPointer.h>
 
-#include "Scheduler/RefreshRateConfigs.h"
+#include "Fps.h"
 
 namespace android {
 
@@ -34,14 +34,12 @@
 class Layer;
 class SurfaceFlinger;
 
-using RefreshRate = scheduler::RefreshRateConfigs::RefreshRate;
-
 class RefreshRateOverlay {
 public:
     RefreshRateOverlay(SurfaceFlinger&, bool showSpinner);
 
     void setViewport(ui::Size);
-    void changeRefreshRate(const RefreshRate&);
+    void changeRefreshRate(const Fps&);
     void onInvalidate();
     void reset();
 
diff --git a/services/surfaceflinger/Scheduler/HwcStrongTypes.h b/services/surfaceflinger/Scheduler/HwcStrongTypes.h
index 8ba4f20..b6a33a2 100644
--- a/services/surfaceflinger/Scheduler/HwcStrongTypes.h
+++ b/services/surfaceflinger/Scheduler/HwcStrongTypes.h
@@ -18,9 +18,11 @@
 
 #include "StrongTyping.h"
 
+#include <cstddef>
+
 namespace android {
 
 // Strong types for the different indexes as they are referring to a different base.
-using HwcConfigIndexType = StrongTyping<int, struct HwcConfigIndexTypeTag, Compare, Add, Hash>;
+using HwcConfigIndexType = StrongTyping<size_t, struct HwcConfigIndexTypeTag, Compare, Add, Hash>;
 
 } // namespace android
\ No newline at end of file
diff --git a/services/surfaceflinger/Scheduler/RefreshRateConfigs.cpp b/services/surfaceflinger/Scheduler/RefreshRateConfigs.cpp
index c42c812..b02596a 100644
--- a/services/surfaceflinger/Scheduler/RefreshRateConfigs.cpp
+++ b/services/surfaceflinger/Scheduler/RefreshRateConfigs.cpp
@@ -39,14 +39,33 @@
                               toString(layer.seamlessness).c_str(),
                               to_string(layer.desiredRefreshRate).c_str());
 }
+
+std::vector<Fps> constructKnownFrameRates(const DisplayModes& configs) {
+    std::vector<Fps> knownFrameRates = {Fps(24.0f), Fps(30.0f), Fps(45.0f), Fps(60.0f), Fps(72.0f)};
+    knownFrameRates.reserve(knownFrameRates.size() + configs.size());
+
+    // Add all supported refresh rates to the set
+    for (const auto& config : configs) {
+        const auto refreshRate = Fps::fromPeriodNsecs(config->getVsyncPeriod());
+        knownFrameRates.emplace_back(refreshRate);
+    }
+
+    // Sort and remove duplicates
+    std::sort(knownFrameRates.begin(), knownFrameRates.end(), Fps::comparesLess);
+    knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
+                                      Fps::EqualsWithMargin()),
+                          knownFrameRates.end());
+    return knownFrameRates;
+}
+
 } // namespace
 
 using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
 using RefreshRate = RefreshRateConfigs::RefreshRate;
 
 std::string RefreshRate::toString() const {
-    return base::StringPrintf("{id=%d, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
-                              getConfigId().value(), hwcConfig->getId(), getFps().getValue(),
+    return base::StringPrintf("{id=%zu, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
+                              getConfigId().value(), hwcConfig->getHwcId(), getFps().getValue(),
                               hwcConfig->getWidth(), hwcConfig->getHeight(), getConfigGroup());
 }
 
@@ -68,7 +87,7 @@
 }
 
 std::string RefreshRateConfigs::Policy::toString() const {
-    return base::StringPrintf("default config ID: %d, allowGroupSwitching = %d"
+    return base::StringPrintf("default config ID: %zu, allowGroupSwitching = %d"
                               ", primary range: %s, app request range: %s",
                               defaultConfig.value(), allowGroupSwitching,
                               primaryRange.toString().c_str(), appRequestRange.toString().c_str());
@@ -154,9 +173,9 @@
     float score;
 };
 
-const RefreshRate& RefreshRateConfigs::getBestRefreshRate(
-        const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
-        GlobalSignals* outSignalsConsidered) const {
+RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
+                                                   const GlobalSignals& globalSignals,
+                                                   GlobalSignals* outSignalsConsidered) const {
     ATRACE_CALL();
     ALOGV("getBestRefreshRate %zu layers", layers.size());
 
@@ -469,9 +488,20 @@
     return bestRefreshRate;
 }
 
-const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicy() const {
+std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
+        std::optional<HwcConfigIndexType> desiredActiveConfigId, bool timerExpired) const {
     std::lock_guard lock(mLock);
-    return getMinRefreshRateByPolicyLocked();
+
+    const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
+                                                : *mCurrentRefreshRate;
+    const auto& min = *mMinSupportedRefreshRate;
+
+    if (current != min) {
+        const auto& refreshRate = timerExpired ? min : current;
+        return refreshRate.getFps();
+    }
+
+    return {};
 }
 
 const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
@@ -487,7 +517,7 @@
     return *mPrimaryRefreshRates.front();
 }
 
-const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
+RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
     std::lock_guard lock(mLock);
     return getMaxRefreshRateByPolicyLocked();
 }
@@ -506,12 +536,12 @@
     return *mPrimaryRefreshRates.back();
 }
 
-const RefreshRate& RefreshRateConfigs::getCurrentRefreshRate() const {
+RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
     std::lock_guard lock(mLock);
     return *mCurrentRefreshRate;
 }
 
-const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
+RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
     std::lock_guard lock(mLock);
     return getCurrentRefreshRateByPolicyLocked();
 }
@@ -529,20 +559,24 @@
     mCurrentRefreshRate = mRefreshRates.at(configId).get();
 }
 
-RefreshRateConfigs::RefreshRateConfigs(
-        const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs,
-        HwcConfigIndexType currentConfigId)
+RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& configs,
+                                       HwcConfigIndexType currentConfigId)
       : mKnownFrameRates(constructKnownFrameRates(configs)) {
+    updateDisplayConfigs(configs, currentConfigId);
+}
+
+void RefreshRateConfigs::updateDisplayConfigs(const DisplayModes& configs,
+                                              HwcConfigIndexType currentConfigId) {
+    std::lock_guard lock(mLock);
     LOG_ALWAYS_FATAL_IF(configs.empty());
-    LOG_ALWAYS_FATAL_IF(currentConfigId.value() < 0);
     LOG_ALWAYS_FATAL_IF(currentConfigId.value() >= configs.size());
 
+    mRefreshRates.clear();
     for (auto configId = HwcConfigIndexType(0); configId.value() < configs.size(); configId++) {
         const auto& config = configs.at(static_cast<size_t>(configId.value()));
+        const auto fps = Fps::fromPeriodNsecs(config->getVsyncPeriod());
         mRefreshRates.emplace(configId,
-                              std::make_unique<RefreshRate>(configId, config,
-                                                            Fps::fromPeriodNsecs(
-                                                                    config->getVsyncPeriod()),
+                              std::make_unique<RefreshRate>(configId, config, fps,
                                                             RefreshRate::ConstructorTag(0)));
         if (configId == currentConfigId) {
             mCurrentRefreshRate = mRefreshRates.at(configId).get();
@@ -550,7 +584,7 @@
     }
 
     std::vector<const RefreshRate*> sortedConfigs;
-    getSortedRefreshRateList([](const RefreshRate&) { return true; }, &sortedConfigs);
+    getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedConfigs);
     mDisplayManagerPolicy.defaultConfig = currentConfigId;
     mMinSupportedRefreshRate = sortedConfigs.front();
     mMaxSupportedRefreshRate = sortedConfigs.back();
@@ -570,7 +604,7 @@
     constructAvailableRefreshRates();
 }
 
-bool RefreshRateConfigs::isPolicyValid(const Policy& policy) {
+bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
     // defaultConfig must be a valid config, and within the given refresh rate range.
     auto iter = mRefreshRates.find(policy.defaultConfig);
     if (iter == mRefreshRates.end()) {
@@ -588,7 +622,7 @@
 
 status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
     std::lock_guard lock(mLock);
-    if (!isPolicyValid(policy)) {
+    if (!isPolicyValidLocked(policy)) {
         ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
         return BAD_VALUE;
     }
@@ -603,7 +637,7 @@
 
 status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
     std::lock_guard lock(mLock);
-    if (policy && !isPolicyValid(*policy)) {
+    if (policy && !isPolicyValidLocked(*policy)) {
         return BAD_VALUE;
     }
     Policy previousPolicy = *getCurrentPolicyLocked();
@@ -639,14 +673,14 @@
     return false;
 }
 
-void RefreshRateConfigs::getSortedRefreshRateList(
+void RefreshRateConfigs::getSortedRefreshRateListLocked(
         const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
         std::vector<const RefreshRate*>* outRefreshRates) {
     outRefreshRates->clear();
     outRefreshRates->reserve(mRefreshRates.size());
     for (const auto& [type, refreshRate] : mRefreshRates) {
         if (shouldAddRefreshRate(*refreshRate)) {
-            ALOGV("getSortedRefreshRateList: config %d added to list policy",
+            ALOGV("getSortedRefreshRateListLocked: config %zu added to list policy",
                   refreshRate->configId.value());
             outRefreshRates->push_back(refreshRate.get());
         }
@@ -672,8 +706,9 @@
     ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
 
     auto filterRefreshRates = [&](Fps min, Fps max, const char* listName,
-                                  std::vector<const RefreshRate*>* outRefreshRates) {
-        getSortedRefreshRateList(
+                                  std::vector<const RefreshRate*>*
+                                          outRefreshRates) REQUIRES(mLock) {
+        getSortedRefreshRateListLocked(
                 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
                     const auto& hwcConfig = refreshRate.hwcConfig;
 
@@ -706,25 +741,6 @@
                        &mAppRequestRefreshRates);
 }
 
-std::vector<Fps> RefreshRateConfigs::constructKnownFrameRates(
-        const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs) {
-    std::vector<Fps> knownFrameRates = {Fps(24.0f), Fps(30.0f), Fps(45.0f), Fps(60.0f), Fps(72.0f)};
-    knownFrameRates.reserve(knownFrameRates.size() + configs.size());
-
-    // Add all supported refresh rates to the set
-    for (const auto& config : configs) {
-        const auto refreshRate = Fps::fromPeriodNsecs(config->getVsyncPeriod());
-        knownFrameRates.emplace_back(refreshRate);
-    }
-
-    // Sort and remove duplicates
-    std::sort(knownFrameRates.begin(), knownFrameRates.end(), Fps::comparesLess);
-    knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
-                                      Fps::EqualsWithMargin()),
-                          knownFrameRates.end());
-    return knownFrameRates;
-}
-
 Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
     if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
         return *mKnownFrameRates.begin();
@@ -744,7 +760,7 @@
 
 RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
     std::lock_guard lock(mLock);
-    const auto& deviceMin = getMinRefreshRate();
+    const auto& deviceMin = *mMinSupportedRefreshRate;
     const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
     const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
 
diff --git a/services/surfaceflinger/Scheduler/RefreshRateConfigs.h b/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
index e4bbf7f..a5d37c2 100644
--- a/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
+++ b/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
@@ -24,6 +24,7 @@
 #include <optional>
 #include <type_traits>
 
+#include "DisplayHardware/DisplayMode.h"
 #include "DisplayHardware/HWComposer.h"
 #include "Fps.h"
 #include "HwcStrongTypes.h"
@@ -64,12 +65,9 @@
         };
 
     public:
-        RefreshRate(HwcConfigIndexType configId,
-                    std::shared_ptr<const HWC2::Display::Config> config, Fps fps, ConstructorTag)
+        RefreshRate(HwcConfigIndexType configId, DisplayModePtr config, Fps fps, ConstructorTag)
               : configId(configId), hwcConfig(config), fps(std::move(fps)) {}
 
-        RefreshRate(const RefreshRate&) = delete;
-
         HwcConfigIndexType getConfigId() const { return configId; }
         nsecs_t getVsyncPeriod() const { return hwcConfig->getVsyncPeriod(); }
         int32_t getConfigGroup() const { return hwcConfig->getConfigGroup(); }
@@ -103,7 +101,7 @@
         // on the device.
         const HwcConfigIndexType configId;
         // The config itself
-        std::shared_ptr<const HWC2::Display::Config> hwcConfig;
+        DisplayModePtr hwcConfig;
         // Refresh rate in frames per second
         const Fps fps{0.0f};
     };
@@ -111,27 +109,26 @@
     using AllRefreshRatesMapType =
             std::unordered_map<HwcConfigIndexType, std::unique_ptr<const RefreshRate>>;
 
+    struct FpsRange {
+        Fps min{0.0f};
+        Fps max{std::numeric_limits<float>::max()};
+
+        bool operator==(const FpsRange& other) const {
+            return min.equalsWithMargin(other.min) && max.equalsWithMargin(other.max);
+        }
+
+        bool operator!=(const FpsRange& other) const { return !(*this == other); }
+
+        std::string toString() const {
+            return base::StringPrintf("[%s %s]", to_string(min).c_str(), to_string(max).c_str());
+        }
+    };
+
     struct Policy {
     private:
         static constexpr int kAllowGroupSwitchingDefault = false;
 
     public:
-        struct Range {
-            Fps min{0.0f};
-            Fps max{std::numeric_limits<float>::max()};
-
-            bool operator==(const Range& other) const {
-                return min.equalsWithMargin(other.min) && max.equalsWithMargin(other.max);
-            }
-
-            bool operator!=(const Range& other) const { return !(*this == other); }
-
-            std::string toString() const {
-                return base::StringPrintf("[%s %s]", to_string(min).c_str(),
-                                          to_string(max).c_str());
-            }
-        };
-
         // The default config, used to ensure we only initiate display config switches within the
         // same config group as defaultConfigId's group.
         HwcConfigIndexType defaultConfig;
@@ -140,29 +137,29 @@
         // The primary refresh rate range represents display manager's general guidance on the
         // display configs we'll consider when switching refresh rates. Unless we get an explicit
         // signal from an app, we should stay within this range.
-        Range primaryRange;
+        FpsRange primaryRange;
         // The app request refresh rate range allows us to consider more display configs when
         // switching refresh rates. Although we should generally stay within the primary range,
         // specific considerations, such as layer frame rate settings specified via the
         // setFrameRate() api, may cause us to go outside the primary range. We never go outside the
         // app request range. The app request range will be greater than or equal to the primary
         // refresh rate range, never smaller.
-        Range appRequestRange;
+        FpsRange appRequestRange;
 
         Policy() = default;
 
-        Policy(HwcConfigIndexType defaultConfig, const Range& range)
+        Policy(HwcConfigIndexType defaultConfig, const FpsRange& range)
               : Policy(defaultConfig, kAllowGroupSwitchingDefault, range, range) {}
 
-        Policy(HwcConfigIndexType defaultConfig, bool allowGroupSwitching, const Range& range)
+        Policy(HwcConfigIndexType defaultConfig, bool allowGroupSwitching, const FpsRange& range)
               : Policy(defaultConfig, allowGroupSwitching, range, range) {}
 
-        Policy(HwcConfigIndexType defaultConfig, const Range& primaryRange,
-               const Range& appRequestRange)
+        Policy(HwcConfigIndexType defaultConfig, const FpsRange& primaryRange,
+               const FpsRange& appRequestRange)
               : Policy(defaultConfig, kAllowGroupSwitchingDefault, primaryRange, appRequestRange) {}
 
         Policy(HwcConfigIndexType defaultConfig, bool allowGroupSwitching,
-               const Range& primaryRange, const Range& appRequestRange)
+               const FpsRange& primaryRange, const FpsRange& appRequestRange)
               : defaultConfig(defaultConfig),
                 allowGroupSwitching(allowGroupSwitching),
                 primaryRange(primaryRange),
@@ -258,35 +255,35 @@
     //   globalSignals - global state of touch and idle
     //   outSignalsConsidered - An output param that tells the caller whether the refresh rate was
     //                          chosen based on touch boost and/or idle timer.
-    const RefreshRate& getBestRefreshRate(const std::vector<LayerRequirement>& layers,
-                                          const GlobalSignals& globalSignals,
-                                          GlobalSignals* outSignalsConsidered = nullptr) const
+    RefreshRate getBestRefreshRate(const std::vector<LayerRequirement>& layers,
+                                   const GlobalSignals& globalSignals,
+                                   GlobalSignals* outSignalsConsidered = nullptr) const
             EXCLUDES(mLock);
 
-    // Returns the lowest refresh rate supported by the device. This won't change at runtime.
-    const RefreshRate& getMinRefreshRate() const { return *mMinSupportedRefreshRate; }
+    FpsRange getSupportedRefreshRateRange() const EXCLUDES(mLock) {
+        std::lock_guard lock(mLock);
+        return {mMinSupportedRefreshRate->getFps(), mMaxSupportedRefreshRate->getFps()};
+    }
 
-    // Returns the lowest refresh rate according to the current policy. May change at runtime. Only
-    // uses the primary range, not the app request range.
-    const RefreshRate& getMinRefreshRateByPolicy() const EXCLUDES(mLock);
-
-    // Returns the highest refresh rate supported by the device. This won't change at runtime.
-    const RefreshRate& getMaxRefreshRate() const { return *mMaxSupportedRefreshRate; }
+    std::optional<Fps> onKernelTimerChanged(std::optional<HwcConfigIndexType> desiredActiveConfigId,
+                                            bool timerExpired) const EXCLUDES(mLock);
 
     // Returns the highest refresh rate according to the current policy. May change at runtime. Only
     // uses the primary range, not the app request range.
-    const RefreshRate& getMaxRefreshRateByPolicy() const EXCLUDES(mLock);
+    RefreshRate getMaxRefreshRateByPolicy() const EXCLUDES(mLock);
 
     // Returns the current refresh rate
-    const RefreshRate& getCurrentRefreshRate() const EXCLUDES(mLock);
+    RefreshRate getCurrentRefreshRate() const EXCLUDES(mLock);
 
     // Returns the current refresh rate, if allowed. Otherwise the default that is allowed by
     // the policy.
-    const RefreshRate& getCurrentRefreshRateByPolicy() const;
+    RefreshRate getCurrentRefreshRateByPolicy() const;
 
-    // Returns the refresh rate that corresponds to a HwcConfigIndexType. This won't change at
+    // Returns the refresh rate that corresponds to a HwcConfigIndexType. This may change at
     // runtime.
-    const RefreshRate& getRefreshRateFromConfigId(HwcConfigIndexType configId) const {
+    // TODO(b/159590486) An invalid config id may be given here if the dipslay configs have changed.
+    RefreshRate getRefreshRateFromConfigId(HwcConfigIndexType configId) const EXCLUDES(mLock) {
+        std::lock_guard lock(mLock);
         return *mRefreshRates.at(configId);
     };
 
@@ -299,13 +296,18 @@
     // Returns a known frame rate that is the closest to frameRate
     Fps findClosestKnownFrameRate(Fps frameRate) const;
 
-    RefreshRateConfigs(const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs,
-                       HwcConfigIndexType currentConfigId);
+    RefreshRateConfigs(const DisplayModes& configs, HwcConfigIndexType currentConfigId);
+
+    void updateDisplayConfigs(const DisplayModes& configs, HwcConfigIndexType currentConfig)
+            EXCLUDES(mLock);
 
     // Returns whether switching configs (refresh rate or resolution) is possible.
     // TODO(b/158780872): Consider HAL support, and skip frame rate detection if the configs only
     // differ in resolution.
-    bool canSwitch() const { return mRefreshRates.size() > 1; }
+    bool canSwitch() const EXCLUDES(mLock) {
+        std::lock_guard lock(mLock);
+        return mRefreshRates.size() > 1;
+    }
 
     // Class to enumerate options around toggling the kernel timer on and off. We have an option
     // for no change to avoid extra calls to kernel.
@@ -334,12 +336,10 @@
     friend class RefreshRateConfigsTest;
 
     void constructAvailableRefreshRates() REQUIRES(mLock);
-    static std::vector<Fps> constructKnownFrameRates(
-            const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs);
 
-    void getSortedRefreshRateList(
+    void getSortedRefreshRateListLocked(
             const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
-            std::vector<const RefreshRate*>* outRefreshRates);
+            std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock);
 
     // Returns the refresh rate with the highest score in the collection specified from begin
     // to end. If there are more than one with the same highest refresh rate, the first one is
@@ -364,7 +364,7 @@
     const RefreshRate& getCurrentRefreshRateByPolicyLocked() const REQUIRES(mLock);
 
     const Policy* getCurrentPolicyLocked() const REQUIRES(mLock);
-    bool isPolicyValid(const Policy& policy);
+    bool isPolicyValidLocked(const Policy& policy) const REQUIRES(mLock);
 
     // Return the display refresh rate divider to match the layer
     // frame rate, or 0 if the display refresh rate is not a multiple of the
@@ -376,9 +376,9 @@
     float calculateLayerScoreLocked(const LayerRequirement&, const RefreshRate&,
                                     bool isSeamlessSwitch) const REQUIRES(mLock);
 
-    // The list of refresh rates, indexed by display config ID. This must not change after this
+    // The list of refresh rates, indexed by display config ID. This may change after this
     // object is initialized.
-    AllRefreshRatesMapType mRefreshRates;
+    AllRefreshRatesMapType mRefreshRates GUARDED_BY(mLock);
 
     // The list of refresh rates in the primary range of the current policy, ordered by vsyncPeriod
     // (the first element is the lowest refresh rate).
@@ -398,9 +398,9 @@
     std::optional<Policy> mOverridePolicy GUARDED_BY(mLock);
 
     // The min and max refresh rates supported by the device.
-    // This will not change at runtime.
-    const RefreshRate* mMinSupportedRefreshRate;
-    const RefreshRate* mMaxSupportedRefreshRate;
+    // This may change at runtime.
+    const RefreshRate* mMinSupportedRefreshRate GUARDED_BY(mLock);
+    const RefreshRate* mMaxSupportedRefreshRate GUARDED_BY(mLock);
 
     mutable std::mutex mLock;
 
diff --git a/services/surfaceflinger/Scheduler/Scheduler.cpp b/services/surfaceflinger/Scheduler/Scheduler.cpp
index 18c899b..92786fd 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.cpp
+++ b/services/surfaceflinger/Scheduler/Scheduler.cpp
@@ -564,21 +564,23 @@
 void Scheduler::registerLayer(Layer* layer) {
     if (!mLayerHistory) return;
 
+    scheduler::LayerHistory::LayerVoteType voteType;
+
     if (layer->getWindowType() == InputWindowInfo::Type::STATUS_BAR) {
-        mLayerHistory->registerLayer(layer, scheduler::LayerHistory::LayerVoteType::NoVote);
+        voteType = scheduler::LayerHistory::LayerVoteType::NoVote;
     } else if (!mOptions.useContentDetection) {
         // If the content detection feature is off, all layers are registered at Max. We still keep
         // the layer history, since we use it for other features (like Frame Rate API), so layers
         // still need to be registered.
-        mLayerHistory->registerLayer(layer, scheduler::LayerHistory::LayerVoteType::Max);
+        voteType = scheduler::LayerHistory::LayerVoteType::Max;
+    } else if (layer->getWindowType() == InputWindowInfo::Type::WALLPAPER) {
+        // Running Wallpaper at Min is considered as part of content detection.
+        voteType = scheduler::LayerHistory::LayerVoteType::Min;
     } else {
-        if (layer->getWindowType() == InputWindowInfo::Type::WALLPAPER) {
-            // Running Wallpaper at Min is considered as part of content detection.
-            mLayerHistory->registerLayer(layer, scheduler::LayerHistory::LayerVoteType::Min);
-        } else {
-            mLayerHistory->registerLayer(layer, scheduler::LayerHistory::LayerVoteType::Heuristic);
-        }
+        voteType = scheduler::LayerHistory::LayerVoteType::Heuristic;
     }
+
+    mLayerHistory->registerLayer(layer, voteType);
 }
 
 void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime,
@@ -612,7 +614,7 @@
         mFeatures.contentRequirements = summary;
 
         newConfigId = calculateRefreshRateConfigIndexType(&consideredSignals);
-        auto& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
+        auto newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
         frameRateOverridesChanged =
                 updateFrameRateOverrides(consideredSignals, newRefreshRate.getFps());
 
@@ -629,7 +631,7 @@
         }
     }
     if (frameRateChanged) {
-        auto& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
+        auto newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
         mSchedulerCallback.changeRefreshRate(newRefreshRate,
                                              consideredSignals.idle ? ConfigEvent::None
                                                                     : ConfigEvent::Changed);
diff --git a/services/surfaceflinger/Scheduler/StrongTyping.h b/services/surfaceflinger/Scheduler/StrongTyping.h
index 6a60257..a05c123 100644
--- a/services/surfaceflinger/Scheduler/StrongTyping.h
+++ b/services/surfaceflinger/Scheduler/StrongTyping.h
@@ -62,8 +62,8 @@
 
 template <typename T, typename W, template <typename> class... Ability>
 struct StrongTyping : Ability<StrongTyping<T, W, Ability...>>... {
-    StrongTyping() : mValue(0) {}
-    explicit StrongTyping(T const& value) : mValue(value) {}
+    constexpr StrongTyping() = default;
+    constexpr explicit StrongTyping(T const& value) : mValue(value) {}
     StrongTyping(StrongTyping const&) = default;
     StrongTyping& operator=(StrongTyping const&) = default;
     explicit inline operator T() const { return mValue; }
@@ -75,7 +75,7 @@
     }
 
 private:
-    T mValue;
+    T mValue{0};
 };
 } // namespace android
 
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 59b3824..a6531e1 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -226,7 +226,7 @@
     ~UnnecessaryLock() RELEASE() {}
 };
 
-// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
+// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
 constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
 
 float getDensityFromProperty(const char* property, bool required) {
@@ -904,14 +904,14 @@
 
     configs->clear();
 
-    for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
+    for (const auto& mode : getHwComposer().getModes(*displayId)) {
         DisplayConfig config;
 
-        auto width = hwConfig->getWidth();
-        auto height = hwConfig->getHeight();
+        auto width = mode->getWidth();
+        auto height = mode->getHeight();
 
-        auto xDpi = hwConfig->getDpiX();
-        auto yDpi = hwConfig->getDpiY();
+        auto xDpi = mode->getDpiX();
+        auto yDpi = mode->getDpiY();
 
         if (isInternal &&
             (internalDisplayOrientation == ui::ROTATION_90 ||
@@ -930,14 +930,14 @@
             config.yDpi = yDpi;
         }
 
-        const nsecs_t period = hwConfig->getVsyncPeriod();
+        const nsecs_t period = mode->getVsyncPeriod();
         config.refreshRate = Fps::fromPeriodNsecs(period).getValue();
 
         const auto vsyncConfigSet =
                 mVsyncConfiguration->getConfigsForRefreshRate(Fps(config.refreshRate));
         config.appVsyncOffset = vsyncConfigSet.late.appOffset;
         config.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
-        config.configGroup = hwConfig->getConfigGroup();
+        config.configGroup = mode->getConfigGroup();
 
         // This is how far in advance a buffer must be queued for
         // presentation at a given time.  If you want a buffer to appear
@@ -995,7 +995,7 @@
 
 void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
     ATRACE_CALL();
-    auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
+    auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
     ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
 
     std::lock_guard<std::mutex> lock(mActiveConfigLock);
@@ -1030,7 +1030,7 @@
     }
 
     if (mRefreshRateOverlay) {
-        mRefreshRateOverlay->changeRefreshRate(refreshRate);
+        mRefreshRateOverlay->changeRefreshRate(refreshRate.getFps());
     }
 }
 
@@ -1076,14 +1076,14 @@
         return;
     }
 
-    auto& oldRefreshRate =
+    auto oldRefreshRate =
             mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
 
     std::lock_guard<std::mutex> lock(mActiveConfigLock);
     mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
     display->setActiveConfig(mUpcomingActiveConfig.configId);
 
-    auto& refreshRate =
+    auto refreshRate =
             mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
     mRefreshRateStats->setRefreshRate(refreshRate.getFps());
 
@@ -1126,9 +1126,9 @@
         return;
     }
 
-    auto& refreshRate =
+    auto refreshRate =
             mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
-    ALOGV("performSetActiveConfig changing active config to %d(%s)",
+    ALOGV("performSetActiveConfig changing active config to %zu(%s)",
           refreshRate.getConfigId().value(), refreshRate.getName().c_str());
     const auto display = getDefaultDisplayDeviceLocked();
     if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
@@ -1158,13 +1158,12 @@
 
     hal::VsyncPeriodChangeTimeline outTimeline;
     auto status =
-            getHwComposer().setActiveConfigWithConstraints(displayId,
-                                                           mUpcomingActiveConfig.configId.value(),
-                                                           constraints, &outTimeline);
+            getHwComposer().setActiveModeWithConstraints(displayId, mUpcomingActiveConfig.configId,
+                                                         constraints, &outTimeline);
     if (status != NO_ERROR) {
-        // setActiveConfigWithConstraints may fail if a hotplug event is just about
+        // setActiveModeWithConstraints may fail if a hotplug event is just about
         // to be sent. We just log the error in this case.
-        ALOGW("setActiveConfigWithConstraints failed: %d", status);
+        ALOGW("setActiveModeWithConstraints failed: %d", status);
         return;
     }
 
@@ -1618,7 +1617,7 @@
 
     // Don't do any updating if the current fps is the same as the new one.
     if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
-        ALOGV("Skipping config %d as it is not part of allowed configs",
+        ALOGV("Skipping config %zu as it is not part of allowed configs",
               refreshRate.getConfigId().value());
         return;
     }
@@ -1663,7 +1662,7 @@
 }
 
 void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
-    // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
+    // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
     // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
 }
 
@@ -1914,17 +1913,19 @@
 
 bool SurfaceFlinger::handleMessageTransaction() {
     ATRACE_CALL();
-
-    if (getTransactionFlags(eTransactionFlushNeeded)) {
-        flushPendingTransactionQueues();
-        flushTransactionQueue();
-    }
     uint32_t transactionFlags = peekTransactionFlags();
+
+    bool flushedATransaction = flushTransactionQueues();
+
     bool runHandleTransaction =
-            ((transactionFlags & (~eTransactionFlushNeeded)) != 0) || mForceTraversal;
+            (transactionFlags && (transactionFlags != eTransactionFlushNeeded)) ||
+            flushedATransaction ||
+            mForceTraversal;
 
     if (runHandleTransaction) {
         handleTransaction(eTransactionMask);
+    } else {
+        getTransactionFlags(eTransactionFlushNeeded);
     }
 
     if (transactionFlushNeeded()) {
@@ -2472,7 +2473,7 @@
                                                     Dataspace::UNKNOWN});
     if (!state.isVirtual()) {
         const auto physicalId = display->getPhysicalId();
-        auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(physicalId));
+        auto activeConfigId = getHwComposer().getActiveMode(physicalId)->getId();
         display->setActiveConfig(activeConfigId);
         display->setDeviceProductInfo(state.physical->deviceProductInfo);
     }
@@ -2492,7 +2493,7 @@
     ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
     if (state.physical) {
         const auto& activeConfig =
-                getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
+                getCompositionEngine().getHwComposer().getActiveMode(state.physical->id);
         width = activeConfig->getWidth();
         height = activeConfig->getHeight();
         pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
@@ -2619,7 +2620,10 @@
             // TODO(b/175678251) Call a listener instead.
             if (currentState.physical->hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
                 const auto displayId = currentState.physical->id;
-                const auto configs = getHwComposer().getConfigs(displayId);
+                const auto configs = getHwComposer().getModes(displayId);
+                const auto currentConfig = getHwComposer().getActiveMode(displayId)->getId();
+                // TODO(b/175678215) Handle the case when currentConfig is not in configs
+                mRefreshRateConfigs->updateDisplayConfigs(configs, currentConfig);
                 mVsyncConfiguration->reset();
                 updatePhaseConfiguration(mRefreshRateConfigs->getCurrentRefreshRate());
                 if (mRefreshRateOverlay) {
@@ -2826,6 +2830,7 @@
         });
     }
 
+    commitInputWindowCommands();
     commitTransaction();
 }
 
@@ -2866,6 +2871,11 @@
                                                                      : nullptr);
 }
 
+void SurfaceFlinger::commitInputWindowCommands() {
+    mInputWindowCommands.merge(mPendingInputWindowCommands);
+    mPendingInputWindowCommands.clear();
+}
+
 void SurfaceFlinger::updateCursorAsync() {
     compositionengine::CompositionRefreshArgs refreshArgs;
     for (const auto& [_, display] : ON_MAIN_THREAD(mDisplays)) {
@@ -2904,11 +2914,9 @@
         return;
     }
 
-    auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
-    mRefreshRateConfigs =
-            std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
-                                                                    primaryDisplayId),
-                                                            currentConfig);
+    auto currentConfig = getHwComposer().getActiveMode(primaryDisplayId)->getId();
+    const auto modes = getHwComposer().getModes(primaryDisplayId);
+    mRefreshRateConfigs = std::make_unique<scheduler::RefreshRateConfigs>(modes, currentConfig);
     const auto& currRefreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig);
     mRefreshRateStats =
             std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate.getFps(),
@@ -3229,55 +3237,55 @@
     mForceTraversal = true;
 }
 
-void SurfaceFlinger::flushPendingTransactionQueues() {
+bool SurfaceFlinger::flushTransactionQueues() {
     // to prevent onHandleDestroyed from being called while the lock is held,
     // we must keep a copy of the transactions (specifically the composer
     // states) around outside the scope of the lock
     std::vector<const TransactionState> transactions;
+    bool flushedATransaction = false;
     {
-        Mutex::Autolock _l(mQueueLock);
+        Mutex::Autolock _l(mStateLock);
 
-        auto it = mPendingTransactionQueues.begin();
-        while (it != mPendingTransactionQueues.end()) {
+        auto it = mTransactionQueues.begin();
+        while (it != mTransactionQueues.end()) {
             auto& [applyToken, transactionQueue] = *it;
 
             while (!transactionQueue.empty()) {
                 const auto& transaction = transactionQueue.front();
                 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
                                                    transaction.states)) {
+                    setTransactionFlags(eTransactionFlushNeeded);
                     break;
                 }
                 transactions.push_back(transaction);
+                applyTransactionState(transaction.frameTimelineVsyncId, transaction.states,
+                                      transaction.displays, transaction.flags,
+                                      mPendingInputWindowCommands, transaction.desiredPresentTime,
+                                      transaction.isAutoTimestamp, transaction.buffer,
+                                      transaction.postTime, transaction.privileged,
+                                      transaction.hasListenerCallbacks,
+                                      transaction.listenerCallbacks, transaction.originPid,
+                                      transaction.originUid, transaction.id, /*isMainThread*/ true);
                 transactionQueue.pop();
+                flushedATransaction = true;
             }
 
             if (transactionQueue.empty()) {
-                it = mPendingTransactionQueues.erase(it);
-                mTransactionQueueCV.broadcast();
+                it = mTransactionQueues.erase(it);
+                mTransactionCV.broadcast();
             } else {
                 it = std::next(it, 1);
             }
         }
     }
-
-    {
-        Mutex::Autolock _l(mStateLock);
-        for (const auto& transaction : transactions) {
-            applyTransactionState(transaction.frameTimelineVsyncId, transaction.states,
-                                  transaction.displays, transaction.flags, mInputWindowCommands,
-                                  transaction.desiredPresentTime, transaction.isAutoTimestamp,
-                                  transaction.buffer, transaction.postTime, transaction.privileged,
-                                  transaction.hasListenerCallbacks, transaction.listenerCallbacks,
-                                  transaction.originPid, transaction.originUid, transaction.id);
-        }
-    }
+    return flushedATransaction;
 }
 
 bool SurfaceFlinger::transactionFlushNeeded() {
-    Mutex::Autolock _l(mQueueLock);
-    return !mPendingTransactionQueues.empty();
+    return !mTransactionQueues.empty();
 }
 
+
 bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
                                                    const Vector<ComposerState>& states,
                                                    bool updateTransactionCounters) {
@@ -3299,8 +3307,6 @@
         if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
           ready = false;
         }
-
-        Mutex::Autolock _l(mStateLock);
         sp<Layer> layer = nullptr;
         if (s.surface) {
             layer = fromHandleLocked(s.surface).promote();
@@ -3313,8 +3319,9 @@
             ready = false;
         }
         if (updateTransactionCounters) {
-            // See BufferStateLayer::mPendingBufferTransactions
-            if (layer) layer->incrementPendingBufferCount();
+              // See BufferStateLayer::mPendingBufferTransactions
+              if (layer) layer->incrementPendingBufferCount();
+
         }
     }
     return ready;
@@ -3331,153 +3338,90 @@
     const int64_t postTime = systemTime();
 
     bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
-    {
-        Mutex::Autolock _l(mQueueLock);
 
-        // If its TransactionQueue already has a pending TransactionState or if it is pending
-        auto itr = mPendingTransactionQueues.find(applyToken);
-        // if this is an animation frame, wait until prior animation frame has
-        // been applied by SF
-        if (flags & eAnimation) {
-            while (itr != mPendingTransactionQueues.end() ||
-                   (!mTransactionQueue.empty() && mAnimTransactionPending)) {
-                status_t err = mTransactionQueueCV.waitRelative(mQueueLock, s2ns(5));
-                if (CC_UNLIKELY(err != NO_ERROR)) {
-                    ALOGW_IF(err == TIMED_OUT,
-                             "setTransactionState timed out "
-                             "waiting for animation frame to apply");
-                    break;
-                }
-                itr = mPendingTransactionQueues.find(applyToken);
+    Mutex::Autolock _l(mStateLock);
+
+    // If its TransactionQueue already has a pending TransactionState or if it is pending
+    auto itr = mTransactionQueues.find(applyToken);
+    // if this is an animation frame, wait until prior animation frame has
+    // been applied by SF
+    if (flags & eAnimation) {
+        while (itr != mTransactionQueues.end()) {
+            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
+            if (CC_UNLIKELY(err != NO_ERROR)) {
+                ALOGW_IF(err == TIMED_OUT,
+                         "setTransactionState timed out "
+                         "waiting for animation frame to apply");
+                break;
             }
+            itr = mTransactionQueues.find(applyToken);
         }
-
-        const bool pendingTransactions = itr != mPendingTransactionQueues.end();
-        // Expected present time is computed and cached on invalidate, so it may be stale.
-        if (!pendingTransactions) {
-            const auto now = systemTime();
-            const bool nextVsyncPending = now < mExpectedPresentTime.load();
-            const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(now);
-            mExpectedPresentTime = calculateExpectedPresentTime(stats);
-            // The transaction might arrive just before the next vsync but after
-            // invalidate was called. In that case we need to get the next vsync
-            // afterwards.
-            if (nextVsyncPending) {
-                mExpectedPresentTime += stats.vsyncPeriod;
-            }
-        }
-
-        // TODO(b/159125966): Remove eEarlyWakeup completly as no client should use this flag
-        if (flags & eEarlyWakeup) {
-            ALOGW("eEarlyWakeup is deprecated. Use eExplicitEarlyWakeup[Start|End]");
-        }
-
-        if (!privileged && (flags & (eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd))) {
-            ALOGE("Only WindowManager is allowed to use eExplicitEarlyWakeup[Start|End] flags");
-            flags &= ~(eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd);
-        }
-
-        IPCThreadState* ipc = IPCThreadState::self();
-        const int originPid = ipc->getCallingPid();
-        const int originUid = ipc->getCallingUid();
-
-        // Call transactionIsReadyToBeApplied first in case we need to incrementPendingBufferCount
-        // if the transaction contains a buffer.
-        if (!transactionIsReadyToBeApplied(isAutoTimestamp ? 0 : desiredPresentTime, states,
-                                           true) ||
-            pendingTransactions) {
-            mPendingTransactionQueues[applyToken].emplace(frameTimelineVsyncId, states, displays,
-                                                          flags, inputWindowCommands,
-                                                          desiredPresentTime, isAutoTimestamp,
-                                                          uncacheBuffer, postTime, privileged,
-                                                          hasListenerCallbacks, listenerCallbacks,
-                                                          originPid, originUid, transactionId);
-
-            setTransactionFlags(eTransactionFlushNeeded);
-            return NO_ERROR;
-        }
-
-        mTransactionQueue.emplace_back(frameTimelineVsyncId, states, displays, flags,
-                                       inputWindowCommands, desiredPresentTime, isAutoTimestamp,
-                                       uncacheBuffer, postTime, privileged, hasListenerCallbacks,
-                                       listenerCallbacks, originPid, originUid, transactionId);
     }
 
-    const auto schedule = [](uint32_t flags) {
-        if (flags & eEarlyWakeup) return TransactionSchedule::Early;
-        if (flags & eExplicitEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
-        if (flags & eExplicitEarlyWakeupStart) return TransactionSchedule::EarlyStart;
-        return TransactionSchedule::Late;
-    }(flags);
-    setTransactionFlags(eTransactionFlushNeeded, schedule);
+    const bool pendingTransactions = itr != mTransactionQueues.end();
+    // Expected present time is computed and cached on invalidate, so it may be stale.
+    if (!pendingTransactions) {
+        const auto now = systemTime();
+        const bool nextVsyncPending = now < mExpectedPresentTime.load();
+        const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(now);
+        mExpectedPresentTime = calculateExpectedPresentTime(stats);
+        // The transaction might arrive just before the next vsync but after
+        // invalidate was called. In that case we need to get the next vsync
+        // afterwards.
+        if (nextVsyncPending) {
+            mExpectedPresentTime += stats.vsyncPeriod;
+        }
+    }
 
-    // if this is a synchronous transaction, wait for it to take effect
-    // before returning.
-    const bool synchronous = flags & eSynchronous;
-    const bool syncInput = inputWindowCommands.syncInputWindows;
-    if (!synchronous && !syncInput) {
+    IPCThreadState* ipc = IPCThreadState::self();
+    const int originPid = ipc->getCallingPid();
+    const int originUid = ipc->getCallingUid();
+
+    // Call transactionIsReadyToBeApplied first in case we need to incrementPendingBufferCount
+    // if the transaction contains a buffer.
+    if (!transactionIsReadyToBeApplied(isAutoTimestamp ? 0 : desiredPresentTime, states, true) ||
+        pendingTransactions) {
+        mTransactionQueues[applyToken].emplace(frameTimelineVsyncId, states, displays, flags,
+                                               desiredPresentTime, isAutoTimestamp, uncacheBuffer,
+                                               postTime, privileged, hasListenerCallbacks,
+                                               listenerCallbacks, originPid, originUid,
+                                               transactionId);
+        setTransactionFlags(eTransactionFlushNeeded);
         return NO_ERROR;
     }
 
-    // Handle synchronous cases.
-    {
-        Mutex::Autolock _l(mStateLock);
-        if (synchronous) {
-            mTransactionPending = true;
-        }
-        if (syncInput) {
-            mPendingSyncInputWindows = true;
-        }
+    applyTransactionState(frameTimelineVsyncId, states, displays, flags, inputWindowCommands,
+                          desiredPresentTime, isAutoTimestamp, uncacheBuffer, postTime, privileged,
+                          hasListenerCallbacks, listenerCallbacks, originPid, originUid,
+                          transactionId, /*isMainThread*/ false);
+    return NO_ERROR;
+}
 
-        // applyTransactionState can be called by either the main SF thread or by
-        // another process through setTransactionState.  While a given process may wish
-        // to wait on synchronous transactions, the main SF thread should never
-        // be blocked.  Therefore, we only wait if isMainThread is false.
-        while (mTransactionPending || mPendingSyncInputWindows) {
+void SurfaceFlinger::applyTransactionState(
+        int64_t frameTimelineVsyncId, const Vector<ComposerState>& states,
+        const Vector<DisplayState>& displays, uint32_t flags,
+        const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
+        bool isAutoTimestamp, const client_cache_t& uncacheBuffer, const int64_t postTime,
+        bool privileged, bool hasListenerCallbacks,
+        const std::vector<ListenerCallbacks>& listenerCallbacks, int originPid, int originUid,
+        uint64_t transactionId, bool isMainThread) {
+    uint32_t transactionFlags = 0;
+
+    if (flags & eAnimation) {
+        // For window updates that are part of an animation we must wait for
+        // previous animation "frames" to be handled.
+        while (!isMainThread && mAnimTransactionPending) {
             status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
             if (CC_UNLIKELY(err != NO_ERROR)) {
                 // just in case something goes wrong in SF, return to the
-                // called after a few seconds.
-                ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
-                mTransactionPending = false;
-                mPendingSyncInputWindows = false;
+                // caller after a few seconds.
+                ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
+                        "waiting for previous animation frame");
+                mAnimTransactionPending = false;
                 break;
             }
         }
     }
-    return NO_ERROR;
-}
-
-void SurfaceFlinger::flushTransactionQueue() {
-    std::vector<TransactionState> transactionQueue;
-    {
-        Mutex::Autolock _l(mQueueLock);
-        if (!mTransactionQueue.empty()) {
-            transactionQueue.swap(mTransactionQueue);
-        }
-        mTransactionQueueCV.broadcast();
-    }
-
-    Mutex::Autolock _l(mStateLock);
-    for (const auto& t : transactionQueue) {
-        applyTransactionState(t.frameTimelineVsyncId, t.states, t.displays, t.flags,
-                              t.inputWindowCommands, t.desiredPresentTime, t.isAutoTimestamp,
-                              t.buffer, t.postTime, t.privileged, t.hasListenerCallbacks,
-                              t.listenerCallbacks, t.originPid, t.originUid, t.id);
-    }
-}
-
-void SurfaceFlinger::applyTransactionState(int64_t frameTimelineVsyncId,
-                                           const Vector<ComposerState>& states,
-                                           const Vector<DisplayState>& displays, uint32_t flags,
-                                           const InputWindowCommands& inputWindowCommands,
-                                           const int64_t desiredPresentTime, bool isAutoTimestamp,
-                                           const client_cache_t& uncacheBuffer,
-                                           const int64_t postTime, bool privileged,
-                                           bool hasListenerCallbacks,
-                                           const std::vector<ListenerCallbacks>& listenerCallbacks,
-                                           int originPid, int originUid, uint64_t transactionId) {
-    uint32_t transactionFlags = 0;
 
     for (const DisplayState& display : displays) {
         transactionFlags |= setDisplayStateLocked(display);
@@ -3536,25 +3480,80 @@
         transactionFlags = eTransactionNeeded;
     }
 
+    // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
+    // so we don't have to wake up again next frame to preform an uneeded traversal.
+    if (isMainThread && (transactionFlags & eTraversalNeeded)) {
+        transactionFlags = transactionFlags & (~eTraversalNeeded);
+        mForceTraversal = true;
+    }
+
+    const auto schedule = [](uint32_t flags) {
+        if (flags & eEarlyWakeup) return TransactionSchedule::Early;
+        if (flags & eExplicitEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
+        if (flags & eExplicitEarlyWakeupStart) return TransactionSchedule::EarlyStart;
+        return TransactionSchedule::Late;
+    }(flags);
+
     if (transactionFlags) {
         if (mInterceptor->isEnabled()) {
             mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
                                           originPid, originUid, transactionId);
         }
 
-        // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
-        // so we don't have to wake up again next frame to preform an unnecessary traversal.
-        if (transactionFlags & eTraversalNeeded) {
-            transactionFlags = transactionFlags & (~eTraversalNeeded);
-            mForceTraversal = true;
+        // TODO(b/159125966): Remove eEarlyWakeup completly as no client should use this flag
+        if (flags & eEarlyWakeup) {
+            ALOGW("eEarlyWakeup is deprecated. Use eExplicitEarlyWakeup[Start|End]");
         }
-        if (transactionFlags) {
-            setTransactionFlags(transactionFlags);
+
+        if (!privileged && (flags & (eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd))) {
+            ALOGE("Only WindowManager is allowed to use eExplicitEarlyWakeup[Start|End] flags");
+            flags &= ~(eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd);
         }
 
+        // this triggers the transaction
+        setTransactionFlags(transactionFlags, schedule);
+
         if (flags & eAnimation) {
             mAnimTransactionPending = true;
         }
+
+        // if this is a synchronous transaction, wait for it to take effect
+        // before returning.
+        const bool synchronous = flags & eSynchronous;
+        const bool syncInput = inputWindowCommands.syncInputWindows;
+        if (!synchronous && !syncInput) {
+            return;
+        }
+
+        if (synchronous) {
+            mTransactionPending = true;
+        }
+        if (syncInput) {
+            mPendingSyncInputWindows = true;
+        }
+
+
+        // applyTransactionState can be called by either the main SF thread or by
+        // another process through setTransactionState.  While a given process may wish
+        // to wait on synchronous transactions, the main SF thread should never
+        // be blocked.  Therefore, we only wait if isMainThread is false.
+        while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
+            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
+            if (CC_UNLIKELY(err != NO_ERROR)) {
+                // just in case something goes wrong in SF, return to the
+                // called after a few seconds.
+                ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
+                mTransactionPending = false;
+                mPendingSyncInputWindows = false;
+                break;
+            }
+        }
+    } else {
+        // Update VsyncModulator state machine even if transaction is not needed.
+        if (schedule == TransactionSchedule::EarlyStart ||
+            schedule == TransactionSchedule::EarlyEnd) {
+            modulateVsync(&VsyncModulator::setTransactionSchedule, schedule);
+        }
     }
 }
 
@@ -3946,7 +3945,7 @@
 }
 
 uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
-    bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
+    bool hasChanges = mPendingInputWindowCommands.merge(inputWindowCommands);
     return hasChanges ? eTraversalNeeded : 0;
 }
 
@@ -4211,11 +4210,9 @@
     d.width = 0;
     d.height = 0;
     displays.add(d);
-
-    // This called on the main thread, apply it directly.
-    applyTransactionState(ISurfaceComposer::INVALID_VSYNC_ID, state, displays, 0,
-                          mInputWindowCommands, systemTime(), true, {}, systemTime(), true, false,
-                          {}, getpid(), getuid(), 0 /* Undefined transactionId */);
+    setTransactionState(ISurfaceComposer::INVALID_VSYNC_ID, state, displays, 0, nullptr,
+                        mPendingInputWindowCommands, systemTime(), true, {}, false, {},
+                        0 /* Undefined transactionId */);
 
     setPowerModeInternal(display, hal::PowerMode::ON);
     const nsecs_t vsyncPeriod = mRefreshRateConfigs->getCurrentRefreshRate().getVsyncPeriod();
@@ -4794,7 +4791,7 @@
 
     if (const auto displayId = getInternalDisplayIdLocked();
         displayId && getHwComposer().isConnected(*displayId)) {
-        const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
+        const auto activeConfig = getHwComposer().getActiveMode(*displayId);
         std::string fps, xDpi, yDpi;
         if (activeConfig) {
             const auto vsyncPeriod = getHwComposer().getDisplayVsyncPeriod(*displayId);
@@ -5324,7 +5321,7 @@
                     ALOGE("No internal display found.");
                     return NO_ERROR;
                 }
-                const auto numConfigs = getHwComposer().getConfigs(*displayId).size();
+                const auto numConfigs = getHwComposer().getModes(*displayId).size();
                 if (newConfigId >= 0 && newConfigId < numConfigs) {
                     const auto displayToken = getInternalDisplayToken();
                     status_t result = setActiveConfig(displayToken, newConfigId);
@@ -5392,7 +5389,7 @@
 
 void SurfaceFlinger::repaintEverything() {
     mRepaintEverything = true;
-    setTransactionFlags(eTransactionNeeded);
+    signalTransaction();
 }
 
 void SurfaceFlinger::repaintEverythingForHWC() {
@@ -5411,16 +5408,16 @@
     // mRefreshRateConfigs->getCurrentRefreshRate()
     static_cast<void>(schedule([=] {
         const auto desiredActiveConfig = getDesiredActiveConfig();
-        const auto& current = desiredActiveConfig
-                ? mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId)
-                : mRefreshRateConfigs->getCurrentRefreshRate();
-        const auto& min = mRefreshRateConfigs->getMinRefreshRate();
+        const std::optional<HwcConfigIndexType> desiredConfigId = desiredActiveConfig
+                ? std::make_optional(desiredActiveConfig->configId)
+                : std::nullopt;
 
-        if (current != min) {
-            const bool timerExpired = mKernelIdleTimerEnabled && expired;
-
+        const bool timerExpired = mKernelIdleTimerEnabled && expired;
+        const auto newRefreshRate =
+                mRefreshRateConfigs->onKernelTimerChanged(desiredConfigId, timerExpired);
+        if (newRefreshRate) {
             if (Mutex::Autolock lock(mStateLock); mRefreshRateOverlay) {
-                mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
+                mRefreshRateOverlay->changeRefreshRate(*newRefreshRate);
             }
             mEventQueue->invalidate();
         }
@@ -6014,7 +6011,7 @@
 
     if (!display->isPrimary()) {
         // TODO(b/144711714): For non-primary displays we should be able to set an active config
-        // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
+        // as well. For now, just call directly to setActiveModeWithConstraints but ideally
         // it should go thru setDesiredActiveConfig, similar to primary display.
         ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
         const auto displayId = display->getPhysicalId();
@@ -6024,8 +6021,8 @@
         constraints.seamlessRequired = false;
 
         hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
-        if (getHwComposer().setActiveConfigWithConstraints(displayId, policy->defaultConfig.value(),
-                                                           constraints, &timeline) < 0) {
+        if (getHwComposer().setActiveModeWithConstraints(displayId, policy->defaultConfig,
+                                                         constraints, &timeline) < 0) {
             return BAD_VALUE;
         }
         if (timeline.refreshRequired) {
@@ -6034,7 +6031,7 @@
 
         display->setActiveConfig(policy->defaultConfig);
         const nsecs_t vsyncPeriod = getHwComposer()
-                                            .getConfigs(displayId)[policy->defaultConfig.value()]
+                                            .getModes(displayId)[policy->defaultConfig.value()]
                                             ->getVsyncPeriod();
         mScheduler->onNonPrimaryDisplayConfigChanged(mAppConnectionHandle, displayId,
                                                      policy->defaultConfig, vsyncPeriod);
@@ -6070,20 +6067,20 @@
     toggleKernelIdleTimer();
 
     auto configId = mScheduler->getPreferredConfigId();
-    auto& preferredRefreshRate = configId
+    auto preferredRefreshRate = configId
             ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
             // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
             : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
-    ALOGV("trying to switch to Scheduler preferred config %d (%s)",
+    ALOGV("trying to switch to Scheduler preferred config %zu (%s)",
           preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
 
     if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
-        ALOGV("switching to Scheduler preferred config %d",
+        ALOGV("switching to Scheduler preferred config %zu",
               preferredRefreshRate.getConfigId().value());
         setDesiredActiveConfig(
                 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
     } else {
-        LOG_ALWAYS_FATAL("Desired config not allowed: %d",
+        LOG_ALWAYS_FATAL("Desired config not allowed: %zu",
                          preferredRefreshRate.getConfigId().value());
     }
 
@@ -6155,9 +6152,10 @@
         return INVALID_OPERATION;
     } else {
         const auto displayId = display->getPhysicalId();
-        *outDefaultConfig = getHwComposer().getActiveConfigIndex(displayId);
+        const auto activeMode = getHwComposer().getActiveMode(displayId);
+        *outDefaultConfig = activeMode->getId().value();
         *outAllowGroupSwitching = false;
-        auto vsyncPeriod = getHwComposer().getActiveConfig(displayId)->getVsyncPeriod();
+        auto vsyncPeriod = activeMode->getVsyncPeriod();
         *outPrimaryRefreshRateMin = Fps::fromPeriodNsecs(vsyncPeriod).getValue();
         *outPrimaryRefreshRateMax = Fps::fromPeriodNsecs(vsyncPeriod).getValue();
         *outAppRequestRefreshRateMin = Fps::fromPeriodNsecs(vsyncPeriod).getValue();
@@ -6376,7 +6374,8 @@
                 mRefreshRateOverlay->setViewport(display->getSize());
             }
 
-            mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
+            mRefreshRateOverlay->changeRefreshRate(
+                    mRefreshRateConfigs->getCurrentRefreshRate().getFps());
         }
     }));
 }
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index 8f38c5d..7253593 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -99,6 +99,8 @@
 class TimeStats;
 class FrameTracer;
 
+using gui::ScreenCaptureResults;
+
 namespace frametimeline {
 class FrameTimeline;
 }
@@ -434,16 +436,15 @@
     struct TransactionState {
         TransactionState(int64_t frameTimelineVsyncId, const Vector<ComposerState>& composerStates,
                          const Vector<DisplayState>& displayStates, uint32_t transactionFlags,
-                         const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
-                         bool isAutoTimestamp, const client_cache_t& uncacheBuffer,
-                         int64_t postTime, bool privileged, bool hasListenerCallbacks,
+                         int64_t desiredPresentTime, bool isAutoTimestamp,
+                         const client_cache_t& uncacheBuffer, int64_t postTime, bool privileged,
+                         bool hasListenerCallbacks,
                          std::vector<ListenerCallbacks> listenerCallbacks, int originPid,
                          int originUid, uint64_t transactionId)
               : frameTimelineVsyncId(frameTimelineVsyncId),
                 states(composerStates),
                 displays(displayStates),
                 flags(transactionFlags),
-                inputWindowCommands(inputWindowCommands),
                 desiredPresentTime(desiredPresentTime),
                 isAutoTimestamp(isAutoTimestamp),
                 buffer(uncacheBuffer),
@@ -459,7 +460,6 @@
         Vector<ComposerState> states;
         Vector<DisplayState> displays;
         uint32_t flags;
-        InputWindowCommands inputWindowCommands;
         const int64_t desiredPresentTime;
         const bool isAutoTimestamp;
         client_cache_t buffer;
@@ -725,7 +725,6 @@
     /*
      * Transactions
      */
-    void flushTransactionQueue();
     void applyTransactionState(int64_t frameTimelineVsyncId, const Vector<ComposerState>& state,
                                const Vector<DisplayState>& displays, uint32_t flags,
                                const InputWindowCommands& inputWindowCommands,
@@ -733,12 +732,10 @@
                                const client_cache_t& uncacheBuffer, const int64_t postTime,
                                bool privileged, bool hasListenerCallbacks,
                                const std::vector<ListenerCallbacks>& listenerCallbacks,
-                               int originPid, int originUid, uint64_t transactionId)
-            REQUIRES(mStateLock);
+                               int originPid, int originUid, uint64_t transactionId,
+                               bool isMainThread = false) REQUIRES(mStateLock);
     // Returns true if at least one transaction was flushed
     bool flushTransactionQueues();
-    // flush pending transaction that was presented after desiredPresentTime.
-    void flushPendingTransactionQueues();
     // Returns true if there is at least one transaction that needs to be flushed
     bool transactionFlushNeeded();
     uint32_t getTransactionFlags(uint32_t flags);
@@ -756,7 +753,7 @@
     void commitOffscreenLayers();
     bool transactionIsReadyToBeApplied(int64_t desiredPresentTime,
                                        const Vector<ComposerState>& states,
-                                       bool updateTransactionCounters = false);
+                                       bool updateTransactionCounters = false) REQUIRES(mStateLock);
     uint32_t setDisplayStateLocked(const DisplayState& s) REQUIRES(mStateLock);
     uint32_t addInputWindowCommands(const InputWindowCommands& inputWindowCommands)
             REQUIRES(mStateLock);
@@ -1173,11 +1170,8 @@
     uint32_t mTexturePoolSize = 0;
     std::vector<uint32_t> mTexturePool;
 
-    mutable Mutex mQueueLock;
-    Condition mTransactionQueueCV;
-    std::unordered_map<sp<IBinder>, std::queue<TransactionState>, IListenerHash>
-            mPendingTransactionQueues GUARDED_BY(mQueueLock);
-    std::vector<TransactionState> mTransactionQueue GUARDED_BY(mQueueLock);
+    std::unordered_map<sp<IBinder>, std::queue<TransactionState>, IListenerHash> mTransactionQueues;
+
     /*
      * Feature prototyping
      */
@@ -1254,6 +1248,7 @@
     const float mEmulatedDisplayDensity;
 
     sp<os::IInputFlinger> mInputFlinger;
+    InputWindowCommands mPendingInputWindowCommands GUARDED_BY(mStateLock);
     // Should only be accessed by the main thread.
     InputWindowCommands mInputWindowCommands;
 
diff --git a/services/surfaceflinger/tests/LayerState_test.cpp b/services/surfaceflinger/tests/LayerState_test.cpp
index e66df4a..ecfed13 100644
--- a/services/surfaceflinger/tests/LayerState_test.cpp
+++ b/services/surfaceflinger/tests/LayerState_test.cpp
@@ -22,6 +22,8 @@
 #include <gui/LayerState.h>
 
 namespace android {
+using gui::ScreenCaptureResults;
+
 namespace test {
 
 TEST(LayerStateTest, ParcellingDisplayCaptureArgs) {
@@ -86,11 +88,11 @@
     results.result = BAD_VALUE;
 
     Parcel p;
-    results.write(p);
+    results.writeToParcel(&p);
     p.setDataPosition(0);
 
     ScreenCaptureResults results2;
-    results2.read(p);
+    results2.readFromParcel(&p);
 
     // GraphicBuffer object is reallocated so compare the data in the graphic buffer
     // rather than the object itself
diff --git a/services/surfaceflinger/tests/TransactionTestHarnesses.h b/services/surfaceflinger/tests/TransactionTestHarnesses.h
index 3ef63d5..a361b1e 100644
--- a/services/surfaceflinger/tests/TransactionTestHarnesses.h
+++ b/services/surfaceflinger/tests/TransactionTestHarnesses.h
@@ -68,9 +68,6 @@
                                        Rect(displayState.layerStackSpaceRect), Rect(resolution));
                 t.apply();
                 SurfaceComposerClient::Transaction().apply(true);
-                // wait for 3 vsyncs to ensure the buffer is latched.
-                usleep(static_cast<int32_t>(1e6 / displayConfig.refreshRate) * 3);
-
                 BufferItem item;
                 itemConsumer->acquireBuffer(&item, 0, true);
                 auto sc = std::make_unique<ScreenCapture>(item.mGraphicBuffer);
diff --git a/services/surfaceflinger/tests/unittests/Android.bp b/services/surfaceflinger/tests/unittests/Android.bp
index 13c7c8b..a42daae 100644
--- a/services/surfaceflinger/tests/unittests/Android.bp
+++ b/services/surfaceflinger/tests/unittests/Android.bp
@@ -80,7 +80,6 @@
         "VSyncReactorTest.cpp",
         "VsyncConfigurationTest.cpp",
         "mock/DisplayHardware/MockComposer.cpp",
-        "mock/DisplayHardware/MockDisplay.cpp",
         "mock/DisplayHardware/MockPowerAdvisor.cpp",
         "mock/MockEventThread.cpp",
         "mock/MockFrameTimeline.cpp",
diff --git a/services/surfaceflinger/tests/unittests/FrameTimelineTest.cpp b/services/surfaceflinger/tests/unittests/FrameTimelineTest.cpp
index 169698b..e2584e2 100644
--- a/services/surfaceflinger/tests/unittests/FrameTimelineTest.cpp
+++ b/services/surfaceflinger/tests/unittests/FrameTimelineTest.cpp
@@ -33,8 +33,13 @@
 using testing::AtLeast;
 using testing::Contains;
 using FrameTimelineEvent = perfetto::protos::FrameTimelineEvent;
-using ProtoDisplayFrame = perfetto::protos::FrameTimelineEvent_DisplayFrame;
-using ProtoSurfaceFrame = perfetto::protos::FrameTimelineEvent_SurfaceFrame;
+using ProtoExpectedDisplayFrameStart =
+        perfetto::protos::FrameTimelineEvent_ExpectedDisplayFrameStart;
+using ProtoExpectedSurfaceFrameStart =
+        perfetto::protos::FrameTimelineEvent_ExpectedSurfaceFrameStart;
+using ProtoActualDisplayFrameStart = perfetto::protos::FrameTimelineEvent_ActualDisplayFrameStart;
+using ProtoActualSurfaceFrameStart = perfetto::protos::FrameTimelineEvent_ActualSurfaceFrameStart;
+using ProtoFrameEnd = perfetto::protos::FrameTimelineEvent_FrameEnd;
 using ProtoPresentType = perfetto::protos::FrameTimelineEvent_PresentType;
 using ProtoJankType = perfetto::protos::FrameTimelineEvent_JankType;
 
@@ -67,10 +72,11 @@
 
     void SetUp() override {
         mTimeStats = std::make_shared<mock::TimeStats>();
-        mFrameTimeline = std::make_unique<impl::FrameTimeline>(mTimeStats, mSurfaceFlingerPid,
+        mFrameTimeline = std::make_unique<impl::FrameTimeline>(mTimeStats, kSurfaceFlingerPid,
                                                                kTestThresholds);
         mFrameTimeline->registerDataSource();
         mTokenManager = &mFrameTimeline->mTokenManager;
+        mTraceCookieCounter = &mFrameTimeline->mTraceCookieCounter;
         maxDisplayFrames = &mFrameTimeline->mMaxDisplayFrames;
         maxTokenRetentionTime = mTokenManager->kMaxRetentionTime;
     }
@@ -130,22 +136,31 @@
                 a.presentTime == b.presentTime;
     }
 
-    const std::map<int64_t, TokenManagerPrediction>& getPredictions() {
+    const std::map<int64_t, TokenManagerPrediction>& getPredictions() const {
         return mTokenManager->mPredictions;
     }
 
-    uint32_t getNumberOfDisplayFrames() {
+    uint32_t getNumberOfDisplayFrames() const {
         std::lock_guard<std::mutex> lock(mFrameTimeline->mMutex);
         return static_cast<uint32_t>(mFrameTimeline->mDisplayFrames.size());
     }
 
+    int64_t snoopCurrentTraceCookie() const { return mTraceCookieCounter->mTraceCookie; }
+
+    void flushTrace() {
+        using FrameTimelineDataSource = impl::FrameTimeline::FrameTimelineDataSource;
+        FrameTimelineDataSource::Trace(
+                [&](FrameTimelineDataSource::TraceContext ctx) { ctx.Flush(); });
+    }
+
     std::shared_ptr<mock::TimeStats> mTimeStats;
     std::unique_ptr<impl::FrameTimeline> mFrameTimeline;
     impl::TokenManager* mTokenManager;
+    TraceCookieCounter* mTraceCookieCounter;
     FenceToFenceTimeMap fenceFactory;
     uint32_t* maxDisplayFrames;
     nsecs_t maxTokenRetentionTime;
-    pid_t mSurfaceFlingerPid = 666;
+    static constexpr pid_t kSurfaceFlingerPid = 666;
     static constexpr nsecs_t kPresentThreshold =
             std::chrono::duration_cast<std::chrono::nanoseconds>(2ns).count();
     static constexpr nsecs_t kDeadlineThreshold =
@@ -549,7 +564,7 @@
 TEST_F(FrameTimelineTest, tracing_sanityTest) {
     auto tracingSession = getTracingSessionForTest();
     // Global increment
-    EXPECT_CALL(*mTimeStats, incrementJankyFrames(testing::_)).Times(2);
+    EXPECT_CALL(*mTimeStats, incrementJankyFrames(testing::_));
     // Layer specific increment
     EXPECT_CALL(*mTimeStats, incrementJankyFrames(testing::_, testing::_, testing::_));
     auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE);
@@ -574,23 +589,18 @@
     mFrameTimeline->setSfPresent(55, presentFence2);
     presentFence2->signalForTest(55);
 
-    // The SurfaceFrame packet from the first frame is emitted, but not flushed yet. Emitting a new
-    // packet will flush it. To emit a new packet, we'll need to call flushPendingPresentFences()
-    // again, which is done by setSfPresent().
-    addEmptyDisplayFrame();
+    flushTrace();
     tracingSession->StopBlocking();
 
     auto packets = readFrameTimelinePacketsBlocking(tracingSession.get());
-    // Display Frame 1 has two packets - DisplayFrame and a SurfaceFrame.
-    // Display Frame 2 has one packet - DisplayFrame. However, this packet has been emitted but not
-    // flushed through traced, so this is not counted.
-    EXPECT_EQ(packets.size(), 2);
+    // Display Frame 1 has 8 packets - 4 from DisplayFrame and 4 from SurfaceFrame.
+    EXPECT_EQ(packets.size(), 8);
 }
 
 TEST_F(FrameTimelineTest, traceDisplayFrame_invalidTokenDoesNotEmitTracePacket) {
     auto tracingSession = getTracingSessionForTest();
     // Global increment
-    EXPECT_CALL(*mTimeStats, incrementJankyFrames(testing::_)).Times(2);
+    EXPECT_CALL(*mTimeStats, incrementJankyFrames(testing::_));
     auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE);
     auto presentFence2 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE);
 
@@ -608,20 +618,17 @@
     mFrameTimeline->setSfPresent(55, presentFence2);
     presentFence2->signalForTest(60);
 
-    addEmptyDisplayFrame();
+    flushTrace();
     tracingSession->StopBlocking();
 
     auto packets = readFrameTimelinePacketsBlocking(tracingSession.get());
-    // Display Frame 1 has no packets.
-    // Display Frame 2 has one packet - DisplayFrame. However, this packet has
-    // been emitted but not flushed through traced, so this is not counted.
     EXPECT_EQ(packets.size(), 0);
 }
 
 TEST_F(FrameTimelineTest, traceSurfaceFrame_invalidTokenDoesNotEmitTracePacket) {
     auto tracingSession = getTracingSessionForTest();
     // Global increment
-    EXPECT_CALL(*mTimeStats, incrementJankyFrames(testing::_)).Times(2);
+    EXPECT_CALL(*mTimeStats, incrementJankyFrames(testing::_));
     auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE);
     auto presentFence2 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE);
 
@@ -644,21 +651,38 @@
     mFrameTimeline->setSfPresent(55, presentFence2);
     presentFence2->signalForTest(60);
 
-    addEmptyDisplayFrame();
+    flushTrace();
     tracingSession->StopBlocking();
 
     auto packets = readFrameTimelinePacketsBlocking(tracingSession.get());
-    // Display Frame 1 has one packet - DisplayFrame (SurfaceFrame shouldn't be traced since it has
-    // an invalid token).
-    // Display Frame 2 has one packet - DisplayFrame. However, this packet has
-    // been emitted but not flushed through traced, so this is not counted.
-    EXPECT_EQ(packets.size(), 1);
+    // Display Frame 1 has 4 packets (SurfaceFrame shouldn't be traced since it has an invalid
+    // token).
+    EXPECT_EQ(packets.size(), 4);
 }
 
-void validateDisplayFrameEvent(const ProtoDisplayFrame& received, const ProtoDisplayFrame& source) {
+void validateTraceEvent(const ProtoExpectedDisplayFrameStart& received,
+                        const ProtoExpectedDisplayFrameStart& source) {
+    ASSERT_TRUE(received.has_cookie());
+    EXPECT_EQ(received.cookie(), source.cookie());
+
     ASSERT_TRUE(received.has_token());
     EXPECT_EQ(received.token(), source.token());
 
+    ASSERT_TRUE(received.has_pid());
+    EXPECT_EQ(received.pid(), source.pid());
+}
+
+void validateTraceEvent(const ProtoActualDisplayFrameStart& received,
+                        const ProtoActualDisplayFrameStart& source) {
+    ASSERT_TRUE(received.has_cookie());
+    EXPECT_EQ(received.cookie(), source.cookie());
+
+    ASSERT_TRUE(received.has_token());
+    EXPECT_EQ(received.token(), source.token());
+
+    ASSERT_TRUE(received.has_pid());
+    EXPECT_EQ(received.pid(), source.pid());
+
     ASSERT_TRUE(received.has_present_type());
     EXPECT_EQ(received.present_type(), source.present_type());
     ASSERT_TRUE(received.has_on_time_finish());
@@ -667,25 +691,43 @@
     EXPECT_EQ(received.gpu_composition(), source.gpu_composition());
     ASSERT_TRUE(received.has_jank_type());
     EXPECT_EQ(received.jank_type(), source.jank_type());
-
-    ASSERT_TRUE(received.has_expected_start_ns());
-    EXPECT_EQ(received.expected_start_ns(), source.expected_start_ns());
-    ASSERT_TRUE(received.has_expected_end_ns());
-    EXPECT_EQ(received.expected_end_ns(), source.expected_end_ns());
-
-    ASSERT_TRUE(received.has_actual_start_ns());
-    EXPECT_EQ(received.actual_start_ns(), source.actual_start_ns());
-    ASSERT_TRUE(received.has_actual_end_ns());
-    EXPECT_EQ(received.actual_end_ns(), source.actual_end_ns());
 }
 
-void validateSurfaceFrameEvent(const ProtoSurfaceFrame& received, const ProtoSurfaceFrame& source) {
+void validateTraceEvent(const ProtoExpectedSurfaceFrameStart& received,
+                        const ProtoExpectedSurfaceFrameStart& source) {
+    ASSERT_TRUE(received.has_cookie());
+    EXPECT_EQ(received.cookie(), source.cookie());
+
     ASSERT_TRUE(received.has_token());
     EXPECT_EQ(received.token(), source.token());
 
     ASSERT_TRUE(received.has_display_frame_token());
     EXPECT_EQ(received.display_frame_token(), source.display_frame_token());
 
+    ASSERT_TRUE(received.has_pid());
+    EXPECT_EQ(received.pid(), source.pid());
+
+    ASSERT_TRUE(received.has_layer_name());
+    EXPECT_EQ(received.layer_name(), source.layer_name());
+}
+
+void validateTraceEvent(const ProtoActualSurfaceFrameStart& received,
+                        const ProtoActualSurfaceFrameStart& source) {
+    ASSERT_TRUE(received.has_cookie());
+    EXPECT_EQ(received.cookie(), source.cookie());
+
+    ASSERT_TRUE(received.has_token());
+    EXPECT_EQ(received.token(), source.token());
+
+    ASSERT_TRUE(received.has_display_frame_token());
+    EXPECT_EQ(received.display_frame_token(), source.display_frame_token());
+
+    ASSERT_TRUE(received.has_pid());
+    EXPECT_EQ(received.pid(), source.pid());
+
+    ASSERT_TRUE(received.has_layer_name());
+    EXPECT_EQ(received.layer_name(), source.layer_name());
+
     ASSERT_TRUE(received.has_present_type());
     EXPECT_EQ(received.present_type(), source.present_type());
     ASSERT_TRUE(received.has_on_time_finish());
@@ -694,27 +736,17 @@
     EXPECT_EQ(received.gpu_composition(), source.gpu_composition());
     ASSERT_TRUE(received.has_jank_type());
     EXPECT_EQ(received.jank_type(), source.jank_type());
+}
 
-    ASSERT_TRUE(received.has_expected_start_ns());
-    EXPECT_EQ(received.expected_start_ns(), source.expected_start_ns());
-    ASSERT_TRUE(received.has_expected_end_ns());
-    EXPECT_EQ(received.expected_end_ns(), source.expected_end_ns());
-
-    ASSERT_TRUE(received.has_actual_start_ns());
-    EXPECT_EQ(received.actual_start_ns(), source.actual_start_ns());
-    ASSERT_TRUE(received.has_actual_end_ns());
-    EXPECT_EQ(received.actual_end_ns(), source.actual_end_ns());
-
-    ASSERT_TRUE(received.has_layer_name());
-    EXPECT_EQ(received.layer_name(), source.layer_name());
-    ASSERT_TRUE(received.has_pid());
-    EXPECT_EQ(received.pid(), source.pid());
+void validateTraceEvent(const ProtoFrameEnd& received, const ProtoFrameEnd& source) {
+    ASSERT_TRUE(received.has_cookie());
+    EXPECT_EQ(received.cookie(), source.cookie());
 }
 
 TEST_F(FrameTimelineTest, traceDisplayFrame_emitsValidTracePacket) {
     auto tracingSession = getTracingSessionForTest();
     // Global increment
-    EXPECT_CALL(*mTimeStats, incrementJankyFrames(testing::_)).Times(2);
+    EXPECT_CALL(*mTimeStats, incrementJankyFrames(testing::_));
     auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE);
     auto presentFence2 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE);
 
@@ -727,16 +759,27 @@
     mFrameTimeline->setSfPresent(26, presentFence1);
     presentFence1->signalForTest(31);
 
-    ProtoDisplayFrame protoDisplayFrame;
-    protoDisplayFrame.set_token(displayFrameToken1);
-    protoDisplayFrame.set_present_type(ProtoPresentType(FrameTimelineEvent::PRESENT_ON_TIME));
-    protoDisplayFrame.set_on_time_finish(true);
-    protoDisplayFrame.set_gpu_composition(false);
-    protoDisplayFrame.set_jank_type(ProtoJankType(FrameTimelineEvent::JANK_NONE));
-    protoDisplayFrame.set_expected_start_ns(10);
-    protoDisplayFrame.set_expected_end_ns(25);
-    protoDisplayFrame.set_actual_start_ns(20);
-    protoDisplayFrame.set_actual_end_ns(26);
+    int64_t traceCookie = snoopCurrentTraceCookie();
+    ProtoExpectedDisplayFrameStart protoExpectedDisplayFrameStart;
+    protoExpectedDisplayFrameStart.set_cookie(traceCookie + 1);
+    protoExpectedDisplayFrameStart.set_token(displayFrameToken1);
+    protoExpectedDisplayFrameStart.set_pid(kSurfaceFlingerPid);
+
+    ProtoFrameEnd protoExpectedDisplayFrameEnd;
+    protoExpectedDisplayFrameEnd.set_cookie(traceCookie + 1);
+
+    ProtoActualDisplayFrameStart protoActualDisplayFrameStart;
+    protoActualDisplayFrameStart.set_cookie(traceCookie + 2);
+    protoActualDisplayFrameStart.set_token(displayFrameToken1);
+    protoActualDisplayFrameStart.set_pid(kSurfaceFlingerPid);
+    protoActualDisplayFrameStart.set_present_type(
+            ProtoPresentType(FrameTimelineEvent::PRESENT_ON_TIME));
+    protoActualDisplayFrameStart.set_on_time_finish(true);
+    protoActualDisplayFrameStart.set_gpu_composition(false);
+    protoActualDisplayFrameStart.set_jank_type(ProtoJankType(FrameTimelineEvent::JANK_NONE));
+
+    ProtoFrameEnd protoActualDisplayFrameEnd;
+    protoActualDisplayFrameEnd.set_cookie(traceCookie + 2);
 
     // Trigger a flushPresentFence (which will call trace function) by calling setSfPresent for the
     // next frame
@@ -744,30 +787,61 @@
     mFrameTimeline->setSfPresent(55, presentFence2);
     presentFence2->signalForTest(55);
 
-    addEmptyDisplayFrame();
+    flushTrace();
     tracingSession->StopBlocking();
 
     auto packets = readFrameTimelinePacketsBlocking(tracingSession.get());
-    // Display Frame 1 has one packet - DisplayFrame.
-    // Display Frame 2 has one packet - DisplayFrame. However, this packet has been emitted but not
-    // flushed through traced, so this is not counted.
-    EXPECT_EQ(packets.size(), 1);
+    EXPECT_EQ(packets.size(), 4);
 
-    const auto& packet = packets[0];
-    ASSERT_TRUE(packet.has_timestamp());
-    ASSERT_TRUE(packet.has_frame_timeline_event());
+    // Packet - 0 : ExpectedDisplayFrameStart
+    const auto& packet0 = packets[0];
+    ASSERT_TRUE(packet0.has_timestamp());
+    EXPECT_EQ(packet0.timestamp(), 10);
+    ASSERT_TRUE(packet0.has_frame_timeline_event());
 
-    const auto& event = packet.frame_timeline_event();
-    ASSERT_TRUE(event.has_display_frame());
-    ASSERT_FALSE(event.has_surface_frame());
-    const auto& displayFrameEvent = event.display_frame();
-    validateDisplayFrameEvent(displayFrameEvent, protoDisplayFrame);
+    const auto& event0 = packet0.frame_timeline_event();
+    ASSERT_TRUE(event0.has_expected_display_frame_start());
+    const auto& expectedDisplayFrameStart = event0.expected_display_frame_start();
+    validateTraceEvent(expectedDisplayFrameStart, protoExpectedDisplayFrameStart);
+
+    // Packet - 1 : FrameEnd (ExpectedDisplayFrame)
+    const auto& packet1 = packets[1];
+    ASSERT_TRUE(packet1.has_timestamp());
+    EXPECT_EQ(packet1.timestamp(), 25);
+    ASSERT_TRUE(packet1.has_frame_timeline_event());
+
+    const auto& event1 = packet1.frame_timeline_event();
+    ASSERT_TRUE(event1.has_frame_end());
+    const auto& expectedDisplayFrameEnd = event1.frame_end();
+    validateTraceEvent(expectedDisplayFrameEnd, protoExpectedDisplayFrameEnd);
+
+    // Packet - 2 : ActualDisplayFrameStart
+    const auto& packet2 = packets[2];
+    ASSERT_TRUE(packet2.has_timestamp());
+    EXPECT_EQ(packet2.timestamp(), 20);
+    ASSERT_TRUE(packet2.has_frame_timeline_event());
+
+    const auto& event2 = packet2.frame_timeline_event();
+    ASSERT_TRUE(event2.has_actual_display_frame_start());
+    const auto& actualDisplayFrameStart = event2.actual_display_frame_start();
+    validateTraceEvent(actualDisplayFrameStart, protoActualDisplayFrameStart);
+
+    // Packet - 3 : FrameEnd (ActualDisplayFrame)
+    const auto& packet3 = packets[3];
+    ASSERT_TRUE(packet3.has_timestamp());
+    EXPECT_EQ(packet3.timestamp(), 26);
+    ASSERT_TRUE(packet3.has_frame_timeline_event());
+
+    const auto& event3 = packet3.frame_timeline_event();
+    ASSERT_TRUE(event3.has_frame_end());
+    const auto& actualDisplayFrameEnd = event3.frame_end();
+    validateTraceEvent(actualDisplayFrameEnd, protoActualDisplayFrameEnd);
 }
 
 TEST_F(FrameTimelineTest, traceSurfaceFrame_emitsValidTracePacket) {
     auto tracingSession = getTracingSessionForTest();
     // Global increment
-    EXPECT_CALL(*mTimeStats, incrementJankyFrames(testing::_)).Times(2);
+    EXPECT_CALL(*mTimeStats, incrementJankyFrames(testing::_));
     // Layer specific increment
     EXPECT_CALL(*mTimeStats, incrementJankyFrames(testing::_, testing::_, testing::_));
     auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE);
@@ -785,19 +859,33 @@
     surfaceFrame1->setActualQueueTime(15);
     surfaceFrame1->setAcquireFenceTime(20);
 
-    ProtoSurfaceFrame protoSurfaceFrame;
-    protoSurfaceFrame.set_token(surfaceFrameToken);
-    protoSurfaceFrame.set_display_frame_token(displayFrameToken1);
-    protoSurfaceFrame.set_present_type(ProtoPresentType(FrameTimelineEvent::PRESENT_ON_TIME));
-    protoSurfaceFrame.set_on_time_finish(true);
-    protoSurfaceFrame.set_gpu_composition(false);
-    protoSurfaceFrame.set_jank_type(ProtoJankType(FrameTimelineEvent::JANK_NONE));
-    protoSurfaceFrame.set_expected_start_ns(10);
-    protoSurfaceFrame.set_expected_end_ns(25);
-    protoSurfaceFrame.set_actual_start_ns(0);
-    protoSurfaceFrame.set_actual_end_ns(20);
-    protoSurfaceFrame.set_layer_name(sLayerNameOne);
-    protoSurfaceFrame.set_pid(sPidOne);
+    // First 2 cookies will be used by the DisplayFrame
+    int64_t traceCookie = snoopCurrentTraceCookie() + 2;
+
+    ProtoExpectedSurfaceFrameStart protoExpectedSurfaceFrameStart;
+    protoExpectedSurfaceFrameStart.set_cookie(traceCookie + 1);
+    protoExpectedSurfaceFrameStart.set_token(surfaceFrameToken);
+    protoExpectedSurfaceFrameStart.set_display_frame_token(displayFrameToken1);
+    protoExpectedSurfaceFrameStart.set_pid(sPidOne);
+    protoExpectedSurfaceFrameStart.set_layer_name(sLayerNameOne);
+
+    ProtoFrameEnd protoExpectedSurfaceFrameEnd;
+    protoExpectedSurfaceFrameEnd.set_cookie(traceCookie + 1);
+
+    ProtoActualSurfaceFrameStart protoActualSurfaceFrameStart;
+    protoActualSurfaceFrameStart.set_cookie(traceCookie + 2);
+    protoActualSurfaceFrameStart.set_token(surfaceFrameToken);
+    protoActualSurfaceFrameStart.set_display_frame_token(displayFrameToken1);
+    protoActualSurfaceFrameStart.set_pid(sPidOne);
+    protoActualSurfaceFrameStart.set_layer_name(sLayerNameOne);
+    protoActualSurfaceFrameStart.set_present_type(
+            ProtoPresentType(FrameTimelineEvent::PRESENT_ON_TIME));
+    protoActualSurfaceFrameStart.set_on_time_finish(true);
+    protoActualSurfaceFrameStart.set_gpu_composition(false);
+    protoActualSurfaceFrameStart.set_jank_type(ProtoJankType(FrameTimelineEvent::JANK_NONE));
+
+    ProtoFrameEnd protoActualSurfaceFrameEnd;
+    protoActualSurfaceFrameEnd.set_cookie(traceCookie + 2);
 
     // Set up the display frame
     mFrameTimeline->setSfWakeUp(displayFrameToken1, 20, 11);
@@ -812,24 +900,55 @@
     mFrameTimeline->setSfPresent(55, presentFence2);
     presentFence2->signalForTest(55);
 
-    addEmptyDisplayFrame();
+    flushTrace();
     tracingSession->StopBlocking();
 
     auto packets = readFrameTimelinePacketsBlocking(tracingSession.get());
-    // Display Frame 1 has one packet - DisplayFrame and a SurfaceFrame.
-    // Display Frame 2 has one packet - DisplayFrame. However, this packet has been emitted but not
-    // flushed through traced, so this is not counted.
-    EXPECT_EQ(packets.size(), 2);
+    EXPECT_EQ(packets.size(), 8);
 
-    const auto& packet = packets[1];
-    ASSERT_TRUE(packet.has_timestamp());
-    ASSERT_TRUE(packet.has_frame_timeline_event());
+    // Packet - 4 : ExpectedSurfaceFrameStart
+    const auto& packet4 = packets[4];
+    ASSERT_TRUE(packet4.has_timestamp());
+    EXPECT_EQ(packet4.timestamp(), 10);
+    ASSERT_TRUE(packet4.has_frame_timeline_event());
 
-    const auto& event = packet.frame_timeline_event();
-    ASSERT_TRUE(!event.has_display_frame());
-    ASSERT_TRUE(event.has_surface_frame());
-    const auto& surfaceFrameEvent = event.surface_frame();
-    validateSurfaceFrameEvent(surfaceFrameEvent, protoSurfaceFrame);
+    const auto& event4 = packet4.frame_timeline_event();
+    ASSERT_TRUE(event4.has_expected_surface_frame_start());
+    const auto& expectedSurfaceFrameStart = event4.expected_surface_frame_start();
+    validateTraceEvent(expectedSurfaceFrameStart, protoExpectedSurfaceFrameStart);
+
+    // Packet - 5 : FrameEnd (ExpectedSurfaceFrame)
+    const auto& packet5 = packets[5];
+    ASSERT_TRUE(packet5.has_timestamp());
+    EXPECT_EQ(packet5.timestamp(), 25);
+    ASSERT_TRUE(packet5.has_frame_timeline_event());
+
+    const auto& event5 = packet5.frame_timeline_event();
+    ASSERT_TRUE(event5.has_frame_end());
+    const auto& expectedSurfaceFrameEnd = event5.frame_end();
+    validateTraceEvent(expectedSurfaceFrameEnd, protoExpectedSurfaceFrameEnd);
+
+    // Packet - 6 : ActualSurfaceFrameStart
+    const auto& packet6 = packets[6];
+    ASSERT_TRUE(packet6.has_timestamp());
+    EXPECT_EQ(packet6.timestamp(), 10);
+    ASSERT_TRUE(packet6.has_frame_timeline_event());
+
+    const auto& event6 = packet6.frame_timeline_event();
+    ASSERT_TRUE(event6.has_actual_surface_frame_start());
+    const auto& actualSurfaceFrameStart = event6.actual_surface_frame_start();
+    validateTraceEvent(actualSurfaceFrameStart, protoActualSurfaceFrameStart);
+
+    // Packet - 7 : FrameEnd (ActualSurfaceFrame)
+    const auto& packet7 = packets[7];
+    ASSERT_TRUE(packet7.has_timestamp());
+    EXPECT_EQ(packet7.timestamp(), 20);
+    ASSERT_TRUE(packet7.has_frame_timeline_event());
+
+    const auto& event7 = packet7.frame_timeline_event();
+    ASSERT_TRUE(event7.has_frame_end());
+    const auto& actualSurfaceFrameEnd = event7.frame_end();
+    validateTraceEvent(actualSurfaceFrameEnd, protoActualSurfaceFrameEnd);
 }
 
 // Tests for Jank classification
diff --git a/services/surfaceflinger/tests/unittests/HWComposerTest.cpp b/services/surfaceflinger/tests/unittests/HWComposerTest.cpp
index bc1e88a..5bab534 100644
--- a/services/surfaceflinger/tests/unittests/HWComposerTest.cpp
+++ b/services/surfaceflinger/tests/unittests/HWComposerTest.cpp
@@ -190,10 +190,10 @@
                 .WillRepeatedly(DoAll(SetArgPointee<3>(1), Return(V2_1::Error::NONE)));
     }
 
-    void testSetActiveConfigWithConstraintsCommon(bool isVsyncPeriodSwitchSupported);
+    void testSetActiveModeWithConstraintsCommon(bool isVsyncPeriodSwitchSupported);
 };
 
-void HWComposerConfigsTest::testSetActiveConfigWithConstraintsCommon(
+void HWComposerConfigsTest::testSetActiveModeWithConstraintsCommon(
         bool isVsyncPeriodSwitchSupported) {
     EXPECT_CALL(*mHal, getMaxVirtualDisplayCount()).WillOnce(Return(0));
     EXPECT_CALL(*mHal, getCapabilities()).WillOnce(Return(std::vector<hal::Capability>{}));
@@ -229,9 +229,9 @@
     constraints.seamlessRequired = false;
 
     hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
-    constexpr size_t kConfigIndex = 0;
+    constexpr HwcConfigIndexType kConfigIndex(0);
     const auto status =
-            hwc.setActiveConfigWithConstraints(physicalId, kConfigIndex, constraints, &timeline);
+            hwc.setActiveModeWithConstraints(physicalId, kConfigIndex, constraints, &timeline);
     EXPECT_EQ(NO_ERROR, status);
 
     const std::vector<Config> kConfigs{7, 8, 9, 10, 11};
@@ -243,17 +243,18 @@
 
     for (size_t configIndex = 0; configIndex < kConfigs.size(); configIndex++) {
         const auto status =
-                hwc.setActiveConfigWithConstraints(physicalId, configIndex, constraints, &timeline);
+                hwc.setActiveModeWithConstraints(physicalId, HwcConfigIndexType(configIndex),
+                                                 constraints, &timeline);
         EXPECT_EQ(NO_ERROR, status) << "Error when switching to config " << configIndex;
     }
 }
 
-TEST_F(HWComposerConfigsTest, setActiveConfigWithConstraintsWithVsyncSwitchingSupported) {
-    testSetActiveConfigWithConstraintsCommon(/*supported=*/true);
+TEST_F(HWComposerConfigsTest, setActiveModeWithConstraintsWithVsyncSwitchingSupported) {
+    testSetActiveModeWithConstraintsCommon(/*supported=*/true);
 }
 
-TEST_F(HWComposerConfigsTest, setActiveConfigWithConstraintsWithVsyncSwitchingNotSupported) {
-    testSetActiveConfigWithConstraintsCommon(/*supported=*/false);
+TEST_F(HWComposerConfigsTest, setActiveModeWithConstraintsWithVsyncSwitchingNotSupported) {
+    testSetActiveModeWithConstraintsCommon(/*supported=*/false);
 }
 
 } // namespace
diff --git a/services/surfaceflinger/tests/unittests/LayerHistoryTest.cpp b/services/surfaceflinger/tests/unittests/LayerHistoryTest.cpp
index 2ee9c64..5abe38b 100644
--- a/services/surfaceflinger/tests/unittests/LayerHistoryTest.cpp
+++ b/services/surfaceflinger/tests/unittests/LayerHistoryTest.cpp
@@ -110,12 +110,11 @@
                 << "Frame rate is " << frameRate;
     }
 
-    Hwc2::mock::Display mDisplay;
-    RefreshRateConfigs mConfigs{{HWC2::Display::Config::Builder(mDisplay, 0)
+    RefreshRateConfigs mConfigs{{DisplayMode::Builder(0)
                                          .setVsyncPeriod(int32_t(LO_FPS_PERIOD))
                                          .setConfigGroup(0)
                                          .build(),
-                                 HWC2::Display::Config::Builder(mDisplay, 1)
+                                 DisplayMode::Builder(1)
                                          .setVsyncPeriod(int32_t(HI_FPS_PERIOD))
                                          .setConfigGroup(0)
                                          .build()},
diff --git a/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp b/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
index 45f0ee6..27c181d 100644
--- a/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
+++ b/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
@@ -25,13 +25,13 @@
 #include <log/log.h>
 #include <thread>
 
+#include <ui/Size.h>
+
 #include "../../Scheduler/RefreshRateConfigs.h"
 #include "DisplayHardware/HWC2.h"
 #include "Scheduler/RefreshRateConfigs.h"
-#include "mock/DisplayHardware/MockDisplay.h"
 
 using namespace std::chrono_literals;
-using testing::_;
 
 namespace android {
 
@@ -56,6 +56,21 @@
         return refreshRateConfigs.mKnownFrameRates;
     }
 
+    RefreshRate getMinRefreshRateByPolicy(const RefreshRateConfigs& refreshRateConfigs) {
+        std::lock_guard lock(refreshRateConfigs.mLock);
+        return refreshRateConfigs.getMinRefreshRateByPolicyLocked();
+    }
+
+    RefreshRate getMinSupportedRefreshRate(const RefreshRateConfigs& refreshRateConfigs) {
+        std::lock_guard lock(refreshRateConfigs.mLock);
+        return *refreshRateConfigs.mMinSupportedRefreshRate;
+    }
+
+    RefreshRate getMaxSupportedRefreshRate(const RefreshRateConfigs& refreshRateConfigs) {
+        std::lock_guard lock(refreshRateConfigs.mLock);
+        return *refreshRateConfigs.mMaxSupportedRefreshRate;
+    }
+
     // Test config IDs
     static inline const HwcConfigIndexType HWC_CONFIG_ID_60 = HwcConfigIndexType(0);
     static inline const HwcConfigIndexType HWC_CONFIG_ID_90 = HwcConfigIndexType(1);
@@ -66,67 +81,48 @@
     static inline const HwcConfigIndexType HWC_CONFIG_ID_50 = HwcConfigIndexType(6);
 
     // Test configs
-    std::shared_ptr<const HWC2::Display::Config> mConfig60 =
-            createConfig(HWC_CONFIG_ID_60, 0, Fps(60.0f).getPeriodNsecs());
-    std::shared_ptr<const HWC2::Display::Config> mConfig90 =
-            createConfig(HWC_CONFIG_ID_90, 0, Fps(90.0f).getPeriodNsecs());
-    std::shared_ptr<const HWC2::Display::Config> mConfig90DifferentGroup =
+    DisplayModePtr mConfig60 = createConfig(HWC_CONFIG_ID_60, 0, Fps(60.0f).getPeriodNsecs());
+    DisplayModePtr mConfig90 = createConfig(HWC_CONFIG_ID_90, 0, Fps(90.0f).getPeriodNsecs());
+    DisplayModePtr mConfig90DifferentGroup =
             createConfig(HWC_CONFIG_ID_90, 1, Fps(90.0f).getPeriodNsecs());
-    std::shared_ptr<const HWC2::Display::Config> mConfig90DifferentResolution =
-            createConfig(HWC_CONFIG_ID_90, 0, Fps(90.0f).getPeriodNsecs(), 111, 222);
-    std::shared_ptr<const HWC2::Display::Config> mConfig72 =
-            createConfig(HWC_CONFIG_ID_72, 0, Fps(72.0f).getPeriodNsecs());
-    std::shared_ptr<const HWC2::Display::Config> mConfig72DifferentGroup =
+    DisplayModePtr mConfig90DifferentResolution =
+            createConfig(HWC_CONFIG_ID_90, 0, Fps(90.0f).getPeriodNsecs(), ui::Size(111, 222));
+    DisplayModePtr mConfig72 = createConfig(HWC_CONFIG_ID_72, 0, Fps(72.0f).getPeriodNsecs());
+    DisplayModePtr mConfig72DifferentGroup =
             createConfig(HWC_CONFIG_ID_72, 1, Fps(72.0f).getPeriodNsecs());
-    std::shared_ptr<const HWC2::Display::Config> mConfig120 =
-            createConfig(HWC_CONFIG_ID_120, 0, Fps(120.0f).getPeriodNsecs());
-    std::shared_ptr<const HWC2::Display::Config> mConfig120DifferentGroup =
+    DisplayModePtr mConfig120 = createConfig(HWC_CONFIG_ID_120, 0, Fps(120.0f).getPeriodNsecs());
+    DisplayModePtr mConfig120DifferentGroup =
             createConfig(HWC_CONFIG_ID_120, 1, Fps(120.0f).getPeriodNsecs());
-    std::shared_ptr<const HWC2::Display::Config> mConfig30 =
-            createConfig(HWC_CONFIG_ID_30, 0, Fps(30.0f).getPeriodNsecs());
-    std::shared_ptr<const HWC2::Display::Config> mConfig30DifferentGroup =
+    DisplayModePtr mConfig30 = createConfig(HWC_CONFIG_ID_30, 0, Fps(30.0f).getPeriodNsecs());
+    DisplayModePtr mConfig30DifferentGroup =
             createConfig(HWC_CONFIG_ID_30, 1, Fps(30.0f).getPeriodNsecs());
-    std::shared_ptr<const HWC2::Display::Config> mConfig25DifferentGroup =
+    DisplayModePtr mConfig25DifferentGroup =
             createConfig(HWC_CONFIG_ID_25, 1, Fps(25.0f).getPeriodNsecs());
-    std::shared_ptr<const HWC2::Display::Config> mConfig50 =
-            createConfig(HWC_CONFIG_ID_50, 0, Fps(50.0f).getPeriodNsecs());
+    DisplayModePtr mConfig50 = createConfig(HWC_CONFIG_ID_50, 0, Fps(50.0f).getPeriodNsecs());
 
     // Test device configurations
     // The positions of the configs in the arrays below MUST match their IDs. For example,
     // the first config should always be 60Hz, the second 90Hz etc.
-    std::vector<std::shared_ptr<const HWC2::Display::Config>> m60OnlyConfigDevice = {mConfig60};
-    std::vector<std::shared_ptr<const HWC2::Display::Config>> m60_90Device = {mConfig60, mConfig90};
-    std::vector<std::shared_ptr<const HWC2::Display::Config>> m60_90DeviceWithDifferentGroups =
-            {mConfig60, mConfig90DifferentGroup};
-    std::vector<std::shared_ptr<const HWC2::Display::Config>> m60_90DeviceWithDifferentResolutions =
-            {mConfig60, mConfig90DifferentResolution};
-    std::vector<std::shared_ptr<const HWC2::Display::Config>> m60_72_90Device = {mConfig60,
-                                                                                 mConfig90,
-                                                                                 mConfig72};
-    std::vector<std::shared_ptr<const HWC2::Display::Config>> m60_90_72_120Device = {mConfig60,
-                                                                                     mConfig90,
-                                                                                     mConfig72,
-                                                                                     mConfig120};
-    std::vector<std::shared_ptr<const HWC2::Display::Config>> m30_60_72_90_120Device = {mConfig60,
-                                                                                        mConfig90,
-                                                                                        mConfig72,
-                                                                                        mConfig120,
-                                                                                        mConfig30};
-    std::vector<std::shared_ptr<const HWC2::Display::Config>> m30_60Device =
-            {mConfig60, mConfig90DifferentGroup, mConfig72DifferentGroup, mConfig120DifferentGroup,
-             mConfig30};
-    std::vector<std::shared_ptr<const HWC2::Display::Config>> m30_60_72_90Device =
-            {mConfig60, mConfig90, mConfig72, mConfig120DifferentGroup, mConfig30};
-    std::vector<std::shared_ptr<const HWC2::Display::Config>> m30_60_90Device =
-            {mConfig60, mConfig90, mConfig72DifferentGroup, mConfig120DifferentGroup, mConfig30};
-    std::vector<std::shared_ptr<const HWC2::Display::Config>> m25_30_50_60Device =
-            {mConfig60,
-             mConfig90,
-             mConfig72DifferentGroup,
-             mConfig120DifferentGroup,
-             mConfig30DifferentGroup,
-             mConfig25DifferentGroup,
-             mConfig50};
+    DisplayModes m60OnlyConfigDevice = {mConfig60};
+    DisplayModes m60_90Device = {mConfig60, mConfig90};
+    DisplayModes m60_90DeviceWithDifferentGroups = {mConfig60, mConfig90DifferentGroup};
+    DisplayModes m60_90DeviceWithDifferentResolutions = {mConfig60, mConfig90DifferentResolution};
+    DisplayModes m60_72_90Device = {mConfig60, mConfig90, mConfig72};
+    DisplayModes m60_90_72_120Device = {mConfig60, mConfig90, mConfig72, mConfig120};
+    DisplayModes m30_60_72_90_120Device = {mConfig60, mConfig90, mConfig72, mConfig120, mConfig30};
+    DisplayModes m30_60Device = {mConfig60, mConfig90DifferentGroup, mConfig72DifferentGroup,
+                                 mConfig120DifferentGroup, mConfig30};
+    DisplayModes m30_60_72_90Device = {mConfig60, mConfig90, mConfig72, mConfig120DifferentGroup,
+                                       mConfig30};
+    DisplayModes m30_60_90Device = {mConfig60, mConfig90, mConfig72DifferentGroup,
+                                    mConfig120DifferentGroup, mConfig30};
+    DisplayModes m25_30_50_60Device = {mConfig60,
+                                       mConfig90,
+                                       mConfig72DifferentGroup,
+                                       mConfig120DifferentGroup,
+                                       mConfig30DifferentGroup,
+                                       mConfig25DifferentGroup,
+                                       mConfig50};
 
     // Expected RefreshRate objects
     RefreshRate mExpected60Config = {HWC_CONFIG_ID_60, mConfig60, Fps(60),
@@ -147,18 +143,12 @@
                                      RefreshRate::ConstructorTag(0)};
     RefreshRate mExpected120Config = {HWC_CONFIG_ID_120, mConfig120, Fps(120),
                                       RefreshRate::ConstructorTag(0)};
-
-    Hwc2::mock::Display mDisplay;
-
 private:
-    std::shared_ptr<const HWC2::Display::Config> createConfig(HwcConfigIndexType configId,
-                                                              int32_t configGroup,
-                                                              int64_t vsyncPeriod,
-                                                              int32_t hight = -1,
-                                                              int32_t width = -1);
+    DisplayModePtr createConfig(HwcConfigIndexType configId, int32_t configGroup,
+                                int64_t vsyncPeriod, ui::Size resolution = ui::Size());
 };
 
-using Builder = HWC2::Display::Config::Builder;
+using Builder = DisplayMode::Builder;
 
 RefreshRateConfigsTest::RefreshRateConfigsTest() {
     const ::testing::TestInfo* const test_info =
@@ -172,14 +162,14 @@
     ALOGD("**** Tearing down after %s.%s\n", test_info->test_case_name(), test_info->name());
 }
 
-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, hal::HWConfigId(configId.value()))
+DisplayModePtr RefreshRateConfigsTest::createConfig(HwcConfigIndexType configId,
+                                                    int32_t configGroup, int64_t vsyncPeriod,
+                                                    ui::Size resolution) {
+    return DisplayMode::Builder(hal::HWConfigId(configId.value()))
             .setVsyncPeriod(int32_t(vsyncPeriod))
             .setConfigGroup(configGroup)
-            .setHeight(hight)
-            .setWidth(width)
+            .setHeight(resolution.height)
+            .setWidth(resolution.width)
             .build();
 }
 
@@ -209,13 +199,13 @@
             std::make_unique<RefreshRateConfigs>(m60_90Device,
                                                  /*currentConfigId=*/HWC_CONFIG_ID_60);
 
-    const auto& minRate = refreshRateConfigs->getMinRefreshRate();
-    const auto& performanceRate = refreshRateConfigs->getMaxRefreshRate();
+    const auto& minRate = getMinSupportedRefreshRate(*refreshRateConfigs);
+    const auto& performanceRate = getMaxSupportedRefreshRate(*refreshRateConfigs);
 
     ASSERT_EQ(mExpected60Config, minRate);
     ASSERT_EQ(mExpected90Config, performanceRate);
 
-    const auto& minRateByPolicy = refreshRateConfigs->getMinRefreshRateByPolicy();
+    const auto& minRateByPolicy = getMinRefreshRateByPolicy(*refreshRateConfigs);
     const auto& performanceRateByPolicy = refreshRateConfigs->getMaxRefreshRateByPolicy();
     ASSERT_EQ(minRateByPolicy, minRate);
     ASSERT_EQ(performanceRateByPolicy, performanceRate);
@@ -226,9 +216,9 @@
             std::make_unique<RefreshRateConfigs>(m60_90DeviceWithDifferentGroups,
                                                  /*currentConfigId=*/HWC_CONFIG_ID_60);
 
-    const auto& minRate = refreshRateConfigs->getMinRefreshRateByPolicy();
-    const auto& performanceRate = refreshRateConfigs->getMaxRefreshRate();
-    const auto& minRate60 = refreshRateConfigs->getMinRefreshRateByPolicy();
+    const auto& minRate = getMinRefreshRateByPolicy(*refreshRateConfigs);
+    const auto& performanceRate = getMaxSupportedRefreshRate(*refreshRateConfigs);
+    const auto& minRate60 = getMinRefreshRateByPolicy(*refreshRateConfigs);
     const auto& performanceRate60 = refreshRateConfigs->getMaxRefreshRateByPolicy();
 
     ASSERT_EQ(mExpected60Config, minRate);
@@ -239,7 +229,7 @@
               0);
     refreshRateConfigs->setCurrentConfigId(HWC_CONFIG_ID_90);
 
-    const auto& minRate90 = refreshRateConfigs->getMinRefreshRateByPolicy();
+    const auto& minRate90 = getMinRefreshRateByPolicy(*refreshRateConfigs);
     const auto& performanceRate90 = refreshRateConfigs->getMaxRefreshRateByPolicy();
 
     ASSERT_EQ(mExpected90DifferentGroupConfig, performanceRate);
@@ -252,9 +242,9 @@
             std::make_unique<RefreshRateConfigs>(m60_90DeviceWithDifferentResolutions,
                                                  /*currentConfigId=*/HWC_CONFIG_ID_60);
 
-    const auto& minRate = refreshRateConfigs->getMinRefreshRateByPolicy();
-    const auto& performanceRate = refreshRateConfigs->getMaxRefreshRate();
-    const auto& minRate60 = refreshRateConfigs->getMinRefreshRateByPolicy();
+    const auto& minRate = getMinRefreshRateByPolicy(*refreshRateConfigs);
+    const auto& performanceRate = getMaxSupportedRefreshRate(*refreshRateConfigs);
+    const auto& minRate60 = getMinRefreshRateByPolicy(*refreshRateConfigs);
     const auto& performanceRate60 = refreshRateConfigs->getMaxRefreshRateByPolicy();
 
     ASSERT_EQ(mExpected60Config, minRate);
@@ -265,7 +255,7 @@
               0);
     refreshRateConfigs->setCurrentConfigId(HWC_CONFIG_ID_90);
 
-    const auto& minRate90 = refreshRateConfigs->getMinRefreshRateByPolicy();
+    const auto& minRate90 = getMinRefreshRateByPolicy(*refreshRateConfigs);
     const auto& performanceRate90 = refreshRateConfigs->getMaxRefreshRateByPolicy();
 
     ASSERT_EQ(mExpected90DifferentResolutionConfig, performanceRate);
@@ -278,8 +268,8 @@
             std::make_unique<RefreshRateConfigs>(m60_90Device,
                                                  /*currentConfigId=*/HWC_CONFIG_ID_60);
 
-    auto& minRate = refreshRateConfigs->getMinRefreshRateByPolicy();
-    auto& performanceRate = refreshRateConfigs->getMaxRefreshRateByPolicy();
+    auto minRate = getMinRefreshRateByPolicy(*refreshRateConfigs);
+    auto performanceRate = refreshRateConfigs->getMaxRefreshRateByPolicy();
 
     ASSERT_EQ(mExpected60Config, minRate);
     ASSERT_EQ(mExpected90Config, performanceRate);
@@ -287,8 +277,8 @@
     ASSERT_GE(refreshRateConfigs->setDisplayManagerPolicy({HWC_CONFIG_ID_60, {Fps(60), Fps(60)}}),
               0);
 
-    auto& minRate60 = refreshRateConfigs->getMinRefreshRateByPolicy();
-    auto& performanceRate60 = refreshRateConfigs->getMaxRefreshRateByPolicy();
+    auto minRate60 = getMinRefreshRateByPolicy(*refreshRateConfigs);
+    auto performanceRate60 = refreshRateConfigs->getMaxRefreshRateByPolicy();
     ASSERT_EQ(mExpected60Config, minRate60);
     ASSERT_EQ(mExpected60Config, performanceRate60);
 }
@@ -298,20 +288,20 @@
             std::make_unique<RefreshRateConfigs>(m60_90Device,
                                                  /*currentConfigId=*/HWC_CONFIG_ID_60);
     {
-        auto& current = refreshRateConfigs->getCurrentRefreshRate();
+        auto current = refreshRateConfigs->getCurrentRefreshRate();
         EXPECT_EQ(current.getConfigId(), HWC_CONFIG_ID_60);
     }
 
     refreshRateConfigs->setCurrentConfigId(HWC_CONFIG_ID_90);
     {
-        auto& current = refreshRateConfigs->getCurrentRefreshRate();
+        auto current = refreshRateConfigs->getCurrentRefreshRate();
         EXPECT_EQ(current.getConfigId(), HWC_CONFIG_ID_90);
     }
 
     ASSERT_GE(refreshRateConfigs->setDisplayManagerPolicy({HWC_CONFIG_ID_90, {Fps(90), Fps(90)}}),
               0);
     {
-        auto& current = refreshRateConfigs->getCurrentRefreshRate();
+        auto current = refreshRateConfigs->getCurrentRefreshRate();
         EXPECT_EQ(current.getConfigId(), HWC_CONFIG_ID_90);
     }
 }
diff --git a/services/surfaceflinger/tests/unittests/RefreshRateStatsTest.cpp b/services/surfaceflinger/tests/unittests/RefreshRateStatsTest.cpp
index 2188402..4a96fc5 100644
--- a/services/surfaceflinger/tests/unittests/RefreshRateStatsTest.cpp
+++ b/services/surfaceflinger/tests/unittests/RefreshRateStatsTest.cpp
@@ -28,7 +28,6 @@
 #include "Scheduler/HwcStrongTypes.h"
 #include "Scheduler/RefreshRateConfigs.h"
 #include "Scheduler/RefreshRateStats.h"
-#include "mock/DisplayHardware/MockDisplay.h"
 #include "mock/MockTimeStats.h"
 
 using namespace std::chrono_literals;
@@ -50,7 +49,7 @@
     RefreshRateStatsTest();
     ~RefreshRateStatsTest();
 
-    void init(const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs) {
+    void init(const DisplayModes& configs) {
         mRefreshRateConfigs =
                 std::make_unique<RefreshRateConfigs>(configs, /*currentConfig=*/CONFIG_ID_0);
 
@@ -59,14 +58,12 @@
                                                                /*currentPowerMode=*/PowerMode::OFF);
     }
 
-    Hwc2::mock::Display mDisplay;
     mock::TimeStats mTimeStats;
     std::unique_ptr<RefreshRateConfigs> mRefreshRateConfigs;
     std::unique_ptr<RefreshRateStats> mRefreshRateStats;
 
-    std::shared_ptr<const HWC2::Display::Config> createConfig(HwcConfigIndexType configId,
-                                                              int32_t configGroup,
-                                                              int64_t vsyncPeriod);
+    DisplayModePtr createConfig(HwcConfigIndexType configId, int32_t configGroup,
+                                int64_t vsyncPeriod);
 };
 
 RefreshRateStatsTest::RefreshRateStatsTest() {
@@ -81,9 +78,9 @@
     ALOGD("**** Tearing down after %s.%s\n", test_info->test_case_name(), test_info->name());
 }
 
-std::shared_ptr<const HWC2::Display::Config> RefreshRateStatsTest::createConfig(
-        HwcConfigIndexType configId, int32_t configGroup, int64_t vsyncPeriod) {
-    return HWC2::Display::Config::Builder(mDisplay, static_cast<hal::HWConfigId>(configId.value()))
+DisplayModePtr RefreshRateStatsTest::createConfig(HwcConfigIndexType configId, int32_t configGroup,
+                                                  int64_t vsyncPeriod) {
+    return DisplayMode::Builder(static_cast<hal::HWConfigId>(configId.value()))
             .setVsyncPeriod(static_cast<int32_t>(vsyncPeriod))
             .setConfigGroup(configGroup)
             .build();
diff --git a/services/surfaceflinger/tests/unittests/SchedulerTest.cpp b/services/surfaceflinger/tests/unittests/SchedulerTest.cpp
index fb02a33..757c702 100644
--- a/services/surfaceflinger/tests/unittests/SchedulerTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SchedulerTest.cpp
@@ -24,7 +24,6 @@
 #include "Scheduler/RefreshRateConfigs.h"
 #include "TestableScheduler.h"
 #include "TestableSurfaceFlinger.h"
-#include "mock/DisplayHardware/MockDisplay.h"
 #include "mock/MockEventThread.h"
 #include "mock/MockLayer.h"
 #include "mock/MockSchedulerCallback.h"
@@ -52,12 +51,9 @@
 
     SchedulerTest();
 
-    Hwc2::mock::Display mDisplay;
-    const scheduler::RefreshRateConfigs mConfigs{{HWC2::Display::Config::Builder(mDisplay, 0)
-                                                          .setVsyncPeriod(16'666'667)
-                                                          .setConfigGroup(0)
-                                                          .build()},
-                                                 HwcConfigIndexType(0)};
+    const scheduler::RefreshRateConfigs
+            mConfigs{{DisplayMode::Builder(0).setVsyncPeriod(16'666'667).setConfigGroup(0).build()},
+                     HwcConfigIndexType(0)};
 
     mock::SchedulerCallback mSchedulerCallback;
 
diff --git a/services/surfaceflinger/tests/unittests/StrongTypingTest.cpp b/services/surfaceflinger/tests/unittests/StrongTypingTest.cpp
index 5406879..45b7610 100644
--- a/services/surfaceflinger/tests/unittests/StrongTypingTest.cpp
+++ b/services/surfaceflinger/tests/unittests/StrongTypingTest.cpp
@@ -24,7 +24,6 @@
 
 TEST(StrongTypeTest, comparison) {
     using SpunkyType = StrongTyping<int, struct SpunkyTypeTag, Compare>;
-    SpunkyType f2(22);
     SpunkyType f1(10);
 
     EXPECT_TRUE(f1 == f1);
diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
index 22bf2ea..2b8a67d 100644
--- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
+++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
@@ -23,6 +23,7 @@
 #include <compositionengine/impl/Display.h>
 #include <compositionengine/impl/OutputLayerCompositionState.h>
 #include <compositionengine/mock/DisplaySurface.h>
+#include <gui/ScreenCaptureResults.h>
 
 #include "BufferQueueLayer.h"
 #include "BufferStateLayer.h"
@@ -40,7 +41,6 @@
 #include "SurfaceFlingerDefaultFactory.h"
 #include "SurfaceInterceptor.h"
 #include "TestableScheduler.h"
-#include "mock/DisplayHardware/MockDisplay.h"
 #include "mock/MockDisplayIdGenerator.h"
 #include "mock/MockFrameTimeline.h"
 #include "mock/MockFrameTracer.h"
@@ -210,17 +210,12 @@
                         std::unique_ptr<EventThread> appEventThread,
                         std::unique_ptr<EventThread> sfEventThread,
                         ISchedulerCallback* callback = nullptr, bool hasMultipleConfigs = false) {
-        std::vector<std::shared_ptr<const HWC2::Display::Config>> configs{
-                HWC2::Display::Config::Builder(mDisplay, 0)
-                        .setVsyncPeriod(16'666'667)
-                        .setConfigGroup(0)
-                        .build()};
+        DisplayModes configs{
+                DisplayMode::Builder(0).setVsyncPeriod(16'666'667).setConfigGroup(0).build()};
 
         if (hasMultipleConfigs) {
-            configs.emplace_back(HWC2::Display::Config::Builder(mDisplay, 1)
-                                         .setVsyncPeriod(11'111'111)
-                                         .setConfigGroup(0)
-                                         .build());
+            configs.emplace_back(
+                    DisplayMode::Builder(1).setVsyncPeriod(11'111'111).setConfigGroup(0).build());
         }
 
         const auto currConfig = HwcConfigIndexType(0);
@@ -365,7 +360,7 @@
         return mFlinger->SurfaceFlinger::getDisplayNativePrimaries(displayToken, primaries);
     }
 
-    auto& getPendingTransactionQueue() { return mFlinger->mPendingTransactionQueues; }
+    auto& getTransactionQueue() { return mFlinger->mTransactionQueues; }
 
     auto setTransactionState(int64_t frameTimelineVsyncId, const Vector<ComposerState>& states,
                              const Vector<DisplayState>& displays, uint32_t flags,
@@ -381,7 +376,7 @@
                                              listenerCallbacks, transactionId);
     }
 
-    auto flushPendingTransactionQueues() { return mFlinger->flushPendingTransactionQueues(); };
+    auto flushTransactionQueues() { return mFlinger->flushTransactionQueues(); };
 
     auto onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
         return mFlinger->onTransact(code, data, reply, flags);
@@ -469,7 +464,6 @@
         }
 
         auto& mutableIsConnected() { return this->mIsConnected; }
-        auto& mutableConfigs() { return this->mConfigs; }
         auto& mutableLayers() { return this->mLayers; }
     };
 
@@ -544,19 +538,20 @@
             auto display = std::make_unique<HWC2Display>(*composer, *mCapabilities, mHwcDisplayId,
                                                          mHwcDisplayType);
 
-            auto config = HWC2::Display::Config::Builder(*display, mActiveConfig);
-            config.setWidth(mWidth);
-            config.setHeight(mHeight);
-            config.setVsyncPeriod(mRefreshRate);
-            config.setDpiX(mDpiX);
-            config.setDpiY(mDpiY);
-            config.setConfigGroup(mConfigGroup);
-            display->mutableConfigs().emplace(static_cast<int32_t>(mActiveConfig), config.build());
             display->mutableIsConnected() = true;
             display->setPowerMode(mPowerMode);
-
             flinger->mutableHwcDisplayData()[mDisplayId].hwcDisplay = std::move(display);
 
+            auto config = DisplayMode::Builder(mActiveConfig)
+                                  .setWidth(mWidth)
+                                  .setHeight(mHeight)
+                                  .setVsyncPeriod(mRefreshRate)
+                                  .setDpiX(mDpiX)
+                                  .setDpiY(mDpiY)
+                                  .setConfigGroup(mConfigGroup)
+                                  .build();
+            flinger->mutableHwcDisplayData()[mDisplayId].modes.push_back(config);
+
             if (mHwcDisplayType == hal::DisplayType::PHYSICAL) {
                 const auto physicalId = PhysicalDisplayId::tryCast(mDisplayId);
                 LOG_ALWAYS_FATAL_IF(!physicalId);
@@ -703,7 +698,6 @@
     surfaceflinger::test::Factory mFactory;
     sp<SurfaceFlinger> mFlinger = new SurfaceFlinger(mFactory, SurfaceFlinger::SkipInitialization);
     TestableScheduler* mScheduler = nullptr;
-    Hwc2::mock::Display mDisplay;
     mock::DisplayIdGenerator<GpuVirtualDisplayId> mGpuVirtualDisplayIdGenerator;
 };
 
diff --git a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp
index a4a4408..06275c6 100644
--- a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp
+++ b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp
@@ -127,7 +127,7 @@
     }
 
     void NotPlacedOnTransactionQueue(uint32_t flags, bool syncInputWindows) {
-        ASSERT_EQ(0, mFlinger.getPendingTransactionQueue().size());
+        ASSERT_EQ(0, mFlinger.getTransactionQueue().size());
         // called in SurfaceFlinger::signalTransaction
         EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
         EXPECT_CALL(*mVSyncTracker, nextAnticipatedVSyncTimeFrom(_)).WillOnce(Return(systemTime()));
@@ -154,12 +154,12 @@
         } else {
             EXPECT_LE(returnedTime, applicationTime + s2ns(5));
         }
-        auto transactionQueue = mFlinger.getPendingTransactionQueue();
+        auto transactionQueue = mFlinger.getTransactionQueue();
         EXPECT_EQ(0, transactionQueue.size());
     }
 
     void PlaceOnTransactionQueue(uint32_t flags, bool syncInputWindows) {
-        ASSERT_EQ(0, mFlinger.getPendingTransactionQueue().size());
+        ASSERT_EQ(0, mFlinger.getTransactionQueue().size());
         // called in SurfaceFlinger::signalTransaction
         EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
 
@@ -183,12 +183,12 @@
         nsecs_t returnedTime = systemTime();
         EXPECT_LE(returnedTime, applicationSentTime + s2ns(5));
         // This transaction should have been placed on the transaction queue
-        auto transactionQueue = mFlinger.getPendingTransactionQueue();
+        auto transactionQueue = mFlinger.getTransactionQueue();
         EXPECT_EQ(1, transactionQueue.size());
     }
 
     void BlockedByPriorTransaction(uint32_t flags, bool syncInputWindows) {
-        ASSERT_EQ(0, mFlinger.getPendingTransactionQueue().size());
+        ASSERT_EQ(0, mFlinger.getTransactionQueue().size());
         // called in SurfaceFlinger::signalTransaction
         nsecs_t time = systemTime();
         EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
@@ -239,7 +239,7 @@
         }
 
         // check that there is one binder on the pending queue.
-        auto transactionQueue = mFlinger.getPendingTransactionQueue();
+        auto transactionQueue = mFlinger.getTransactionQueue();
         EXPECT_EQ(1, transactionQueue.size());
 
         auto& [applyToken, transactionStates] = *(transactionQueue.begin());
@@ -258,7 +258,7 @@
 };
 
 TEST_F(TransactionApplicationTest, Flush_RemovesFromQueue) {
-    ASSERT_EQ(0, mFlinger.getPendingTransactionQueue().size());
+    ASSERT_EQ(0, mFlinger.getTransactionQueue().size());
     // called in SurfaceFlinger::signalTransaction
     EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
 
@@ -275,7 +275,7 @@
                                  transactionA.isAutoTimestamp, transactionA.uncacheBuffer,
                                  mHasListenerCallbacks, mCallbacks, transactionA.id);
 
-    auto& transactionQueue = mFlinger.getPendingTransactionQueue();
+    auto& transactionQueue = mFlinger.getTransactionQueue();
     ASSERT_EQ(1, transactionQueue.size());
 
     auto& [applyToken, transactionStates] = *(transactionQueue.begin());
@@ -294,9 +294,9 @@
                                  empty.desiredPresentTime, empty.isAutoTimestamp,
                                  empty.uncacheBuffer, mHasListenerCallbacks, mCallbacks, empty.id);
 
-    // flush pending transaction queue should flush as desiredPresentTime has
+    // flush transaction queue should flush as desiredPresentTime has
     // passed
-    mFlinger.flushPendingTransactionQueues();
+    mFlinger.flushTransactionQueues();
 
     EXPECT_EQ(0, transactionQueue.size());
 }
diff --git a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplay.h b/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplay.h
deleted file mode 100644
index a96d9db..0000000
--- a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplay.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-#include <gmock/gmock.h>
-
-#include "DisplayHardware/HWC2.h"
-
-using android::HWC2::Layer;
-
-namespace android::Hwc2::mock {
-
-namespace hal = android::hardware::graphics::composer::hal;
-
-class Display : public HWC2::Display {
-public:
-    using Layer = ::Layer;
-
-    Display();
-    ~Display();
-
-    MOCK_CONST_METHOD0(getId, hal::HWDisplayId());
-    MOCK_CONST_METHOD0(isConnected, bool());
-    MOCK_METHOD1(setConnected, void(bool));
-    MOCK_CONST_METHOD0(getCapabilities, const std::unordered_set<hal::DisplayCapability>&());
-
-    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,
-                       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, hal::Error(std::string*));
-    MOCK_METHOD2(getRequests,
-                 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,
-                       hal::Error(hal::PixelFormat*, hal::Dataspace*, uint8_t*));
-    MOCK_CONST_METHOD3(setDisplayContentSamplingEnabled, hal::Error(bool, uint8_t, uint64_t));
-    MOCK_CONST_METHOD3(getDisplayedContentSample,
-                       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,
-                 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,
-                 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,
-                 hal::Error(uint32_t*, uint32_t*, android::sp<android::Fence>*, uint32_t*));
-    MOCK_METHOD1(setDisplayBrightness, std::future<hal::Error>(float));
-    MOCK_CONST_METHOD1(getDisplayVsyncPeriod, hal::Error(nsecs_t*));
-    MOCK_METHOD3(setActiveConfigWithConstraints,
-                 hal::Error(const std::shared_ptr<const HWC2::Display::Config>&,
-                            const hal::VsyncPeriodChangeConstraints&,
-                            hal::VsyncPeriodChangeTimeline*));
-    MOCK_METHOD1(setAutoLowLatencyMode, hal::Error(bool on));
-    MOCK_CONST_METHOD1(getSupportedContentTypes, hal::Error(std::vector<hal::ContentType>*));
-    MOCK_METHOD1(setContentType, hal::Error(hal::ContentType));
-    MOCK_METHOD1(getClientTargetProperty, hal::Error(hal::ClientTargetProperty*));
-    MOCK_CONST_METHOD1(getConnectionType, hal::Error(android::DisplayConnectionType*));
-    MOCK_CONST_METHOD0(isVsyncPeriodSwitchSupported, bool());
-};
-
-} // namespace android::Hwc2::mock