Merge "Revert "Use arm instruction set with clang 7.0 LTO""
diff --git a/cmds/atrace/atrace.cpp b/cmds/atrace/atrace.cpp
index 1b90579..898aa90 100644
--- a/cmds/atrace/atrace.cpp
+++ b/cmds/atrace/atrace.cpp
@@ -56,7 +56,6 @@
 using std::string;
 
 #define MAX_SYS_FILES 10
-#define MAX_PACKAGES 16
 
 const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
 
@@ -94,6 +93,7 @@
 static const TracingCategory k_categories[] = {
     { "gfx",        "Graphics",         ATRACE_TAG_GRAPHICS, {
         { OPT,      "events/mdss/enable" },
+        { OPT,      "events/sde/enable" },
     } },
     { "input",      "Input",            ATRACE_TAG_INPUT, { } },
     { "view",       "View System",      ATRACE_TAG_VIEW, { } },
@@ -116,6 +116,7 @@
     { "database",   "Database",         ATRACE_TAG_DATABASE, { } },
     { "network",    "Network",          ATRACE_TAG_NETWORK, { } },
     { "adb",        "ADB",              ATRACE_TAG_ADB, { } },
+    { "vibrator",   "Vibrator",         ATRACE_TAG_VIBRATOR, {}},
     { k_coreServiceCategory, "Core services", 0, { } },
     { k_pdxServiceCategory, "PDX services", 0, { } },
     { "sched",      "CPU Scheduling",   0, {
@@ -154,6 +155,9 @@
         { OPT,      "events/power/clock_set_rate/enable" },
         { OPT,      "events/power/clock_disable/enable" },
         { OPT,      "events/power/clock_enable/enable" },
+        { OPT,      "events/clk/clk_set_rate/enable" },
+        { OPT,      "events/clk/clk_disable/enable" },
+        { OPT,      "events/clk/clk_enable/enable" },
         { OPT,      "events/power/cpu_frequency_limits/enable" },
     } },
     { "membus",     "Memory Bus Utilization", 0, {
@@ -598,12 +602,6 @@
 
 static void clearAppProperties()
 {
-    for (int i = 0; i < MAX_PACKAGES; i++) {
-        std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
-        if (!android::base::SetProperty(key, "")) {
-            fprintf(stderr, "failed to clear system property: %s\n", key.c_str());
-        }
-    }
     if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
         fprintf(stderr, "failed to clear system property: %s",
               k_traceAppsNumberProperty);
@@ -617,11 +615,6 @@
     int i = 0;
     char* start = cmdline;
     while (start != NULL) {
-        if (i == MAX_PACKAGES) {
-            fprintf(stderr, "error: only 16 packages could be traced at once\n");
-            clearAppProperties();
-            return false;
-        }
         char* end = strchr(start, ',');
         if (end != NULL) {
             *end = '\0';
@@ -1059,7 +1052,7 @@
     fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
     fprintf(stderr, "options include:\n"
                     "  -a appname      enable app-level tracing for a comma "
-                        "separated list of cmdlines\n"
+                        "separated list of cmdlines; * is a wildcard matching any process\n"
                     "  -b N            use a trace buffer size of N KB\n"
                     "  -c              trace into a circular buffer\n"
                     "  -f filename     use the categories written in a file as space-separated\n"
diff --git a/cmds/atrace/atrace.rc b/cmds/atrace/atrace.rc
index 89ce1e5..3ec0163 100644
--- a/cmds/atrace/atrace.rc
+++ b/cmds/atrace/atrace.rc
@@ -6,6 +6,9 @@
     chmod 0222 /sys/kernel/debug/tracing/trace_marker
     chmod 0222 /sys/kernel/tracing/trace_marker
 
+# Scheduler tracepoints require schedstats=enable
+    write /proc/sys/kernel/sched_schedstats 1
+
 # Grant unix world read/write permissions to kernel tracepoints.
 # Access control to these files is now entirely in selinux policy.
     chmod 0666 /sys/kernel/debug/tracing/trace_clock
diff --git a/cmds/dumpstate/dumpstate.cpp b/cmds/dumpstate/dumpstate.cpp
index f17ac5b..3b1c9b6 100644
--- a/cmds/dumpstate/dumpstate.cpp
+++ b/cmds/dumpstate/dumpstate.cpp
@@ -201,7 +201,7 @@
             continue;
         }
 
-        if (limit_by_mtime && st.st_mtime >= thirty_minutes_ago) {
+        if (limit_by_mtime && st.st_mtime < thirty_minutes_ago) {
             MYLOGI("Excluding stale dump file: %s\n", abs_path.c_str());
             continue;
         }
diff --git a/cmds/installd/InstalldNativeService.cpp b/cmds/installd/InstalldNativeService.cpp
index 0d50b9b..dea6c6c 100644
--- a/cmds/installd/InstalldNativeService.cpp
+++ b/cmds/installd/InstalldNativeService.cpp
@@ -170,6 +170,35 @@
     }
 }
 
+binder::Status checkArgumentPath(const std::string& path) {
+    if (path.empty()) {
+        return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing path");
+    }
+    if (path[0] != '/') {
+        return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+                StringPrintf("Path %s is relative", path.c_str()));
+    }
+    if ((path + '/').find("/../") != std::string::npos) {
+        return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+                StringPrintf("Path %s is shady", path.c_str()));
+    }
+    for (const char& c : path) {
+        if (c == '\0' || c == '\n') {
+            return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+                    StringPrintf("Path %s is malformed", path.c_str()));
+        }
+    }
+    return ok();
+}
+
+binder::Status checkArgumentPath(const std::unique_ptr<std::string>& path) {
+    if (path) {
+        return checkArgumentPath(*path);
+    } else {
+        return ok();
+    }
+}
+
 #define ENFORCE_UID(uid) {                                  \
     binder::Status status = checkUid((uid));                \
     if (!status.isOk()) {                                   \
@@ -192,6 +221,13 @@
     }                                                       \
 }
 
+#define CHECK_ARGUMENT_PATH(path) {                         \
+    binder::Status status = checkArgumentPath((path));      \
+    if (!status.isOk()) {                                   \
+        return status;                                      \
+    }                                                       \
+}
+
 #define ASSERT_PAGE_SIZE_4K() {                             \
     if (getpagesize() != kVerityPageSize) {                 \
         return error("FSVerity only supports 4K pages");     \
@@ -1139,6 +1175,7 @@
 binder::Status InstalldNativeService::rmdex(const std::string& codePath,
         const std::string& instructionSet) {
     ENFORCE_UID(AID_SYSTEM);
+    CHECK_ARGUMENT_PATH(codePath);
     std::lock_guard<std::recursive_mutex> lock(mLock);
 
     char dex_path[PKG_PATH_MAX];
@@ -1398,6 +1435,9 @@
     for (const auto& packageName : packageNames) {
         CHECK_ARGUMENT_PACKAGE_NAME(packageName);
     }
+    for (const auto& codePath : codePaths) {
+        CHECK_ARGUMENT_PATH(codePath);
+    }
     // NOTE: Locking is relaxed on this method, since it's limited to
     // read-only measurements without mutation.
 
@@ -1843,6 +1883,7 @@
         const std::string& profileName, const std::string& codePath, bool* _aidl_return) {
     ENFORCE_UID(AID_SYSTEM);
     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
+    CHECK_ARGUMENT_PATH(codePath);
     std::lock_guard<std::recursive_mutex> lock(mLock);
 
     *_aidl_return = dump_profiles(uid, packageName, profileName, codePath);
@@ -1906,12 +1947,16 @@
         const std::unique_ptr<std::string>& classLoaderContext,
         const std::unique_ptr<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion,
         const std::unique_ptr<std::string>& profileName,
-        const std::unique_ptr<std::string>& dexMetadataPath) {
+        const std::unique_ptr<std::string>& dexMetadataPath,
+        const std::unique_ptr<std::string>& compilationReason) {
     ENFORCE_UID(AID_SYSTEM);
     CHECK_ARGUMENT_UUID(uuid);
+    CHECK_ARGUMENT_PATH(apkPath);
     if (packageName && *packageName != "*") {
         CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
     }
+    CHECK_ARGUMENT_PATH(outputPath);
+    CHECK_ARGUMENT_PATH(dexMetadataPath);
     std::lock_guard<std::recursive_mutex> lock(mLock);
 
     const char* apk_path = apkPath.c_str();
@@ -1924,9 +1969,10 @@
     const char* se_info = getCStr(seInfo);
     const char* profile_name = getCStr(profileName);
     const char* dm_path = getCStr(dexMetadataPath);
+    const char* compilation_reason = getCStr(compilationReason);
     int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
             oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
-            downgrade, targetSdkVersion, profile_name, dm_path);
+            downgrade, targetSdkVersion, profile_name, dm_path, compilation_reason);
     return res ? error(res, "Failed to dexopt") : ok();
 }
 
@@ -1956,6 +2002,7 @@
     ENFORCE_UID(AID_SYSTEM);
     CHECK_ARGUMENT_UUID(uuid);
     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
+    CHECK_ARGUMENT_PATH(nativeLibPath32);
     std::lock_guard<std::recursive_mutex> lock(mLock);
 
     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
@@ -2123,6 +2170,8 @@
 binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
         const std::string& overlayApkPath, int32_t uid) {
     ENFORCE_UID(AID_SYSTEM);
+    CHECK_ARGUMENT_PATH(targetApkPath);
+    CHECK_ARGUMENT_PATH(overlayApkPath);
     std::lock_guard<std::recursive_mutex> lock(mLock);
 
     const char* target_apk = targetApkPath.c_str();
@@ -2208,6 +2257,10 @@
 }
 
 binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
+    ENFORCE_UID(AID_SYSTEM);
+    CHECK_ARGUMENT_PATH(overlayApkPath);
+    std::lock_guard<std::recursive_mutex> lock(mLock);
+
     const char* overlay_apk = overlayApkPath.c_str();
     char idmap_path[PATH_MAX];
 
@@ -2258,6 +2311,7 @@
 binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
         const std::string& instructionSet) {
     ENFORCE_UID(AID_SYSTEM);
+    CHECK_ARGUMENT_PATH(oatDir);
     std::lock_guard<std::recursive_mutex> lock(mLock);
 
     const char* oat_dir = oatDir.c_str();
@@ -2282,6 +2336,7 @@
 
 binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
     ENFORCE_UID(AID_SYSTEM);
+    CHECK_ARGUMENT_PATH(packageDir);
     std::lock_guard<std::recursive_mutex> lock(mLock);
 
     if (validate_apk_path(packageDir.c_str())) {
@@ -2296,6 +2351,8 @@
 binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
         const std::string& fromBase, const std::string& toBase) {
     ENFORCE_UID(AID_SYSTEM);
+    CHECK_ARGUMENT_PATH(fromBase);
+    CHECK_ARGUMENT_PATH(toBase);
     std::lock_guard<std::recursive_mutex> lock(mLock);
 
     const char* relative_path = relativePath.c_str();
@@ -2324,6 +2381,8 @@
 binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
         const std::string& instructionSet, const std::string& outputPath) {
     ENFORCE_UID(AID_SYSTEM);
+    CHECK_ARGUMENT_PATH(apkPath);
+    CHECK_ARGUMENT_PATH(outputPath);
     std::lock_guard<std::recursive_mutex> lock(mLock);
 
     const char* apk_path = apkPath.c_str();
@@ -2337,6 +2396,8 @@
 binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
         const std::string& instructionSet, const std::unique_ptr<std::string>& outputPath) {
     ENFORCE_UID(AID_SYSTEM);
+    CHECK_ARGUMENT_PATH(apkPath);
+    CHECK_ARGUMENT_PATH(outputPath);
     std::lock_guard<std::recursive_mutex> lock(mLock);
 
     const char* apk_path = apkPath.c_str();
@@ -2371,6 +2432,9 @@
 binder::Status InstalldNativeService::installApkVerity(const std::string& filePath,
         const ::android::base::unique_fd& verityInputAshmem) {
     ENFORCE_UID(AID_SYSTEM);
+    CHECK_ARGUMENT_PATH(filePath);
+    std::lock_guard<std::recursive_mutex> lock(mLock);
+
     if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
         return ok();
     }
@@ -2438,6 +2502,9 @@
 binder::Status InstalldNativeService::assertFsverityRootHashMatches(const std::string& filePath,
         const std::vector<uint8_t>& expectedHash) {
     ENFORCE_UID(AID_SYSTEM);
+    CHECK_ARGUMENT_PATH(filePath);
+    std::lock_guard<std::recursive_mutex> lock(mLock);
+
     if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
         return ok();
     }
@@ -2472,8 +2539,9 @@
     ENFORCE_UID(AID_SYSTEM);
     CHECK_ARGUMENT_UUID(volumeUuid);
     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
-
+    CHECK_ARGUMENT_PATH(dexPath);
     std::lock_guard<std::recursive_mutex> lock(mLock);
+
     bool result = android::installd::reconcile_secondary_dex_file(
             dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
     return result ? ok() : error();
@@ -2486,6 +2554,7 @@
     ENFORCE_UID(AID_SYSTEM);
     CHECK_ARGUMENT_UUID(volumeUuid);
     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
+    CHECK_ARGUMENT_PATH(dexPath);
 
     // mLock is not taken here since we will never modify the file system.
     // If a file is modified just as we are reading it this may result in an
@@ -2582,6 +2651,7 @@
         const std::unique_ptr<std::string>& dexMetadata, bool* _aidl_return) {
     ENFORCE_UID(AID_SYSTEM);
     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
+    CHECK_ARGUMENT_PATH(codePath);
     std::lock_guard<std::recursive_mutex> lock(mLock);
 
     *_aidl_return = prepare_app_profile(packageName, userId, appId, profileName, codePath,
diff --git a/cmds/installd/InstalldNativeService.h b/cmds/installd/InstalldNativeService.h
index 22b1d12..2a31967 100644
--- a/cmds/installd/InstalldNativeService.h
+++ b/cmds/installd/InstalldNativeService.h
@@ -86,7 +86,8 @@
             const std::unique_ptr<std::string>& classLoaderContext,
             const std::unique_ptr<std::string>& seInfo, bool downgrade,
             int32_t targetSdkVersion, const std::unique_ptr<std::string>& profileName,
-            const std::unique_ptr<std::string>& dexMetadataPath);
+            const std::unique_ptr<std::string>& dexMetadataPath,
+            const std::unique_ptr<std::string>& compilationReason);
 
     binder::Status rmdex(const std::string& codePath, const std::string& instructionSet);
 
diff --git a/cmds/installd/binder/android/os/IInstalld.aidl b/cmds/installd/binder/android/os/IInstalld.aidl
index e07c847..0c364bd 100644
--- a/cmds/installd/binder/android/os/IInstalld.aidl
+++ b/cmds/installd/binder/android/os/IInstalld.aidl
@@ -53,7 +53,8 @@
             @nullable @utf8InCpp String sharedLibraries,
             @nullable @utf8InCpp String seInfo, boolean downgrade, int targetSdkVersion,
             @nullable @utf8InCpp String profileName,
-            @nullable @utf8InCpp String dexMetadataPath);
+            @nullable @utf8InCpp String dexMetadataPath,
+            @nullable @utf8InCpp String compilationReason);
 
     void rmdex(@utf8InCpp String codePath, @utf8InCpp String instructionSet);
 
diff --git a/cmds/installd/dexopt.cpp b/cmds/installd/dexopt.cpp
index b456507..9f1cd45 100644
--- a/cmds/installd/dexopt.cpp
+++ b/cmds/installd/dexopt.cpp
@@ -223,8 +223,8 @@
         const char* input_file_name, const char* output_file_name, int swap_fd,
         const char* instruction_set, const char* compiler_filter,
         bool debuggable, bool post_bootcomplete, bool background_job_compile, int profile_fd,
-        const char* class_loader_context, int target_sdk_version, bool disable_hidden_api_checks,
-        int dex_metadata_fd) {
+        const char* class_loader_context, int target_sdk_version, bool enable_hidden_api_checks,
+        int dex_metadata_fd, const char* compilation_reason) {
     static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
 
     if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
@@ -423,6 +423,10 @@
 
     std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
 
+    std::string compilation_reason_arg = compilation_reason == nullptr
+            ? ""
+            : std::string("--compilation-reason=") + compilation_reason;
+
     ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
 
     // Disable cdex if update input vdex is true since this combination of options is not
@@ -452,8 +456,9 @@
                      + (disable_cdex ? 1 : 0)
                      + (generate_minidebug_info ? 1 : 0)
                      + (target_sdk_version != 0 ? 2 : 0)
-                     + (disable_hidden_api_checks ? 2 : 0)
-                     + (dex_metadata_fd > -1 ? 1 : 0)];
+                     + (enable_hidden_api_checks ? 2 : 0)
+                     + (dex_metadata_fd > -1 ? 1 : 0)
+                     + (compilation_reason != nullptr ? 1 : 0)];
     int i = 0;
     argv[i++] = dex2oat_bin;
     argv[i++] = zip_fd_arg;
@@ -527,14 +532,18 @@
         argv[i++] = RUNTIME_ARG;
         argv[i++] = target_sdk_version_arg;
     }
-    if (disable_hidden_api_checks) {
+    if (enable_hidden_api_checks) {
         argv[i++] = RUNTIME_ARG;
-        argv[i++] = "-Xno-hidden-api-checks";
+        argv[i++] = "-Xhidden-api-checks";
     }
 
     if (dex_metadata_fd > -1) {
         argv[i++] = dex_metadata_fd_arg.c_str();
     }
+
+    if(compilation_reason != nullptr) {
+        argv[i++] = compilation_reason_arg.c_str();
+    }
     // Do not add after dex2oat_flags, they should override others for debugging.
     argv[i] = NULL;
 
@@ -1865,7 +1874,7 @@
         int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
         const char* volume_uuid, const char* class_loader_context, const char* se_info,
         bool downgrade, int target_sdk_version, const char* profile_name,
-        const char* dex_metadata_path) {
+        const char* dex_metadata_path, const char* compilation_reason) {
     CHECK(pkgname != nullptr);
     CHECK(pkgname[0] != 0);
     if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
@@ -1887,7 +1896,7 @@
     bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
     bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
     bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
-    bool disable_hidden_api_checks = (dexopt_flags & DEXOPT_DISABLE_HIDDEN_API_CHECKS) != 0;
+    bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
 
     // Check if we're dealing with a secondary dex file and if we need to compile it.
     std::string oat_dir_str;
@@ -1993,8 +2002,9 @@
                     reference_profile_fd.get(),
                     class_loader_context,
                     target_sdk_version,
-                    disable_hidden_api_checks,
-                    dex_metadata_fd.get());
+                    enable_hidden_api_checks,
+                    dex_metadata_fd.get(),
+                    compilation_reason);
         _exit(68);   /* only get here on exec failure */
     } else {
         int res = wait_child(pid);
diff --git a/cmds/installd/dexopt.h b/cmds/installd/dexopt.h
index ae1412e..62f9467 100644
--- a/cmds/installd/dexopt.h
+++ b/cmds/installd/dexopt.h
@@ -106,7 +106,7 @@
         int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
         const char* volume_uuid, const char* class_loader_context, const char* se_info,
         bool downgrade, int target_sdk_version, const char* profile_name,
-        const char* dexMetadataPath);
+        const char* dexMetadataPath, const char* compilation_reason);
 
 bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
         const char *apk_path, const char *instruction_set);
diff --git a/cmds/installd/installd_constants.h b/cmds/installd/installd_constants.h
index 9b6714d..06c83e4 100644
--- a/cmds/installd/installd_constants.h
+++ b/cmds/installd/installd_constants.h
@@ -52,7 +52,7 @@
 // Tells the compiler that it is invoked from the background service.  This
 // controls whether extra debugging flags can be used (taking more compile time.)
 constexpr int DEXOPT_IDLE_BACKGROUND_JOB = 1 << 9;
-constexpr int DEXOPT_DISABLE_HIDDEN_API_CHECKS = 1 << 10;
+constexpr int DEXOPT_ENABLE_HIDDEN_API_CHECKS = 1 << 10;
 
 /* all known values for dexopt flags */
 constexpr int DEXOPT_MASK =
@@ -64,7 +64,7 @@
     | DEXOPT_FORCE
     | DEXOPT_STORAGE_CE
     | DEXOPT_STORAGE_DE
-    | DEXOPT_DISABLE_HIDDEN_API_CHECKS;
+    | DEXOPT_ENABLE_HIDDEN_API_CHECKS;
 
 // NOTE: keep in sync with StorageManager
 constexpr int FLAG_STORAGE_DE = 1 << 0;
diff --git a/cmds/installd/otapreopt.cpp b/cmds/installd/otapreopt.cpp
index 72d01a5..899285a 100644
--- a/cmds/installd/otapreopt.cpp
+++ b/cmds/installd/otapreopt.cpp
@@ -79,8 +79,8 @@
 static_assert(DEXOPT_FORCE          == 1 << 6, "DEXOPT_FORCE unexpected.");
 static_assert(DEXOPT_STORAGE_CE     == 1 << 7, "DEXOPT_STORAGE_CE unexpected.");
 static_assert(DEXOPT_STORAGE_DE     == 1 << 8, "DEXOPT_STORAGE_DE unexpected.");
-static_assert(DEXOPT_DISABLE_HIDDEN_API_CHECKS == 1 << 10,
-        "DEXOPT_DISABLE_HIDDEN_API_CHECKS unexpected");
+static_assert(DEXOPT_ENABLE_HIDDEN_API_CHECKS == 1 << 10,
+        "DEXOPT_ENABLE_HIDDEN_API_CHECKS unexpected");
 
 static_assert(DEXOPT_MASK           == 0x5fe, "DEXOPT_MASK unexpected.");
 
@@ -352,7 +352,7 @@
 
         std::string preopted_boot_art_path = StringPrintf("/system/framework/%s/boot.art", isa);
         if (access(preopted_boot_art_path.c_str(), F_OK) == 0) {
-          return PatchoatBootImage(art_path, isa);
+          return PatchoatBootImage(isa_path, isa);
         } else {
           // No preopted boot image. Try to compile.
           return Dex2oatBootImage(boot_classpath_, art_path, oat_path, isa);
@@ -421,14 +421,14 @@
         CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
     }
 
-    bool PatchoatBootImage(const std::string& art_path, const char* isa) const {
+    bool PatchoatBootImage(const std::string& output_dir, const char* isa) const {
         // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
 
         std::vector<std::string> cmd;
         cmd.push_back("/system/bin/patchoat");
 
         cmd.push_back("--input-image-location=/system/framework/boot.art");
-        cmd.push_back(StringPrintf("--output-image-file=%s", art_path.c_str()));
+        cmd.push_back(StringPrintf("--output-image-directory=%s", output_dir.c_str()));
 
         cmd.push_back(StringPrintf("--instruction-set=%s", isa));
 
@@ -582,7 +582,8 @@
                       parameters_.downgrade,
                       parameters_.target_sdk_version,
                       parameters_.profile_name,
-                      parameters_.dex_metadata_path);
+                      parameters_.dex_metadata_path,
+                      parameters_.compilation_reason);
     }
 
     int RunPreopt() {
diff --git a/cmds/installd/otapreopt_parameters.cpp b/cmds/installd/otapreopt_parameters.cpp
index 5b5f522..802d5d7 100644
--- a/cmds/installd/otapreopt_parameters.cpp
+++ b/cmds/installd/otapreopt_parameters.cpp
@@ -112,6 +112,29 @@
     return (input & old_mask) != 0 ? new_mask : 0;
 }
 
+void OTAPreoptParameters::SetDefaultsForPostV1Arguments() {
+    // Set se_info to null. It is only relevant for secondary dex files, which we won't
+    // receive from a v1 A side.
+    se_info = nullptr;
+
+    // Set downgrade to false. It is only relevant when downgrading compiler
+    // filter, which is not the case during ota.
+    downgrade = false;
+
+    // Set target_sdk_version to 0, ie the platform SDK version. This is
+    // conservative and may force some classes to verify at runtime.
+    target_sdk_version = 0;
+
+    // Set the profile name to the primary apk profile.
+    profile_name = "primary.prof";
+
+    // By default we don't have a dex metadata file.
+    dex_metadata_path = nullptr;
+
+    // The compilation reason is ab-ota (match the system property pm.dexopt.ab-ota)
+    compilation_reason = "ab-ota";
+}
+
 bool OTAPreoptParameters::ReadArgumentsV1(const char** argv) {
     // Check for "dexopt".
     if (argv[2] == nullptr) {
@@ -203,20 +226,7 @@
         return false;
     }
 
-    // Set se_info to null. It is only relevant for secondary dex files, which we won't
-    // receive from a v1 A side.
-    se_info = nullptr;
-
-    // Set downgrade to false. It is only relevant when downgrading compiler
-    // filter, which is not the case during ota.
-    downgrade = false;
-
-    // Set target_sdk_version to 0, ie the platform SDK version. This is
-    // conservative and may force some classes to verify at runtime.
-    target_sdk_version = 0;
-
-    // Set the profile name to the primary apk profile.
-    profile_name = "primary.prof";
+    SetDefaultsForPostV1Arguments();
 
     return true;
 }
@@ -229,6 +239,7 @@
         case 4: num_args_expected = 13; break;
         case 5: num_args_expected = 14; break;
         case 6: num_args_expected = 15; break;
+        case 7: num_args_expected = 16; break;
         default:
             LOG(ERROR) << "Don't know how to read arguments for version " << version;
             return false;
@@ -260,17 +271,7 @@
     // The number of arguments is OK.
     // Configure the default values for the parameters that were added after V1.
     // The default values will be overwritten in case they are passed as arguments.
-
-    // Set downgrade to false. It is only relevant when downgrading compiler
-    // filter, which is not the case during ota.
-    downgrade = false;
-
-    // Set target_sdk_version to 0, ie the platform SDK version. This is
-    // conservative and may force some classes to verify at runtime.
-    target_sdk_version = 0;
-
-    // Set the profile name to the primary apk profile.
-    profile_name = "primary.prof";
+    SetDefaultsForPostV1Arguments();
 
     for (size_t param_index = 0; param_index < num_args_actual; ++param_index) {
         const char* param = argv[dexopt_index + 1 + param_index];
@@ -332,11 +333,18 @@
                 break;
 
             case 14:
-                 dex_metadata_path = ParseNull(param);
+                dex_metadata_path = ParseNull(param);
+                break;
+
+            case 15:
+                compilation_reason = ParseNull(param);
+                break;
 
             default:
-                CHECK(false) << "Should not get here. Did you call ReadArguments "
-                        << "with the right expectation?";
+                LOG(FATAL) << "Should not get here. Did you call ReadArguments "
+                        << "with the right expectation? index=" << param_index
+                        << " num_args=" << num_args_actual;
+                return false;
         }
     }
 
diff --git a/cmds/installd/otapreopt_parameters.h b/cmds/installd/otapreopt_parameters.h
index 0f3bb8c..a2f6e44 100644
--- a/cmds/installd/otapreopt_parameters.h
+++ b/cmds/installd/otapreopt_parameters.h
@@ -31,6 +31,7 @@
     bool ReadArgumentsV1(const char** argv);
     bool ReadArgumentsPostV1(uint32_t version, const char** argv, bool versioned);
 
+    void SetDefaultsForPostV1Arguments();
     const char* apk_path;
     uid_t uid;
     const char* pkgName;
@@ -46,6 +47,7 @@
     int target_sdk_version;
     const char* profile_name;
     const char* dex_metadata_path;
+    const char* compilation_reason;
 
     std::string target_slot;
 
@@ -56,4 +58,4 @@
 }  // namespace installd
 }  // namespace android
 
-#endif  //  OTAPREOPT_PARAMETERS_H_
\ No newline at end of file
+#endif  //  OTAPREOPT_PARAMETERS_H_
diff --git a/cmds/installd/tests/installd_dexopt_test.cpp b/cmds/installd/tests/installd_dexopt_test.cpp
index 5a82965..2629144 100644
--- a/cmds/installd/tests/installd_dexopt_test.cpp
+++ b/cmds/installd/tests/installd_dexopt_test.cpp
@@ -264,6 +264,7 @@
         int32_t target_sdk_version = 0;  // default
         std::unique_ptr<std::string> profile_name_ptr = nullptr;
         std::unique_ptr<std::string> dm_path_ptr = nullptr;
+        std::unique_ptr<std::string> compilation_reason_ptr = nullptr;
 
         binder::Status result = service_->dexopt(path,
                                                  uid,
@@ -279,7 +280,8 @@
                                                  downgrade,
                                                  target_sdk_version,
                                                  profile_name_ptr,
-                                                 dm_path_ptr);
+                                                 dm_path_ptr,
+                                                 compilation_reason_ptr);
         ASSERT_EQ(should_binder_call_succeed, result.isOk());
         int expected_access = should_dex_be_compiled ? 0 : -1;
         std::string odex = GetSecondaryDexArtifact(path, "odex");
@@ -369,6 +371,7 @@
         if (dm_path != nullptr) {
             dm_path_ptr.reset(new std::string(dm_path));
         }
+        std::unique_ptr<std::string> compilation_reason_ptr(new std::string("test-reason"));
 
         bool prof_result;
         binder::Status prof_binder_result = service_->prepareAppProfile(
@@ -392,7 +395,8 @@
                                                  downgrade,
                                                  target_sdk_version,
                                                  profile_name_ptr,
-                                                 dm_path_ptr);
+                                                 dm_path_ptr,
+                                                 compilation_reason_ptr);
         ASSERT_EQ(should_binder_call_succeed, result.isOk());
 
         if (!should_binder_call_succeed) {
diff --git a/cmds/installd/tests/installd_otapreopt_test.cpp b/cmds/installd/tests/installd_otapreopt_test.cpp
index 1e8ae42..82bf932 100644
--- a/cmds/installd/tests/installd_otapreopt_test.cpp
+++ b/cmds/installd/tests/installd_otapreopt_test.cpp
@@ -39,8 +39,8 @@
 class OTAPreoptTest : public testing::Test {
 protected:
     virtual void SetUp() {
-        setenv("ANDROID_LOG_TAGS", "*:v", 1);
-        android::base::InitLogging(nullptr);
+        setenv("ANDROID_LOG_TAGS", "*:f", 1);
+        android::base::InitLogging(nullptr, android::base::StderrLogger);
     }
 
     void verifyPackageParameters(const OTAPreoptParameters& params,
@@ -68,7 +68,7 @@
         if (version > 1) {
             ASSERT_STREQ(params.se_info, ParseNull(args[i++]));
         } else {
-            ASSERT_STREQ(params.se_info, nullptr);
+            ASSERT_EQ(params.se_info, nullptr);
         }
         if (version > 2) {
             ASSERT_EQ(params.downgrade, ParseBool(args[i++]));
@@ -88,7 +88,12 @@
         if (version > 5) {
             ASSERT_STREQ(params.dex_metadata_path, ParseNull(args[i++]));
         } else {
-            ASSERT_STREQ(params.dex_metadata_path, nullptr);
+            ASSERT_EQ(params.dex_metadata_path, nullptr);
+        }
+        if (version > 6) {
+            ASSERT_STREQ(params.compilation_reason, ParseNull(args[i++]));
+        } else {
+            ASSERT_STREQ(params.compilation_reason, "ab-ota");
         }
     }
 
@@ -100,6 +105,7 @@
             case 4: return "4";
             case 5: return "5";
             case 6: return "6";
+            case 7: return "7";
         }
         return nullptr;
     }
@@ -138,6 +144,9 @@
         if (version > 5) {
             args.push_back("dex_metadata.dm");  // dex_metadata_path
         }
+        if (version > 6) {
+            args.push_back("ab-ota-test");  // compilation_reason
+        }
         args.push_back(nullptr);  // we have to end with null.
         return args;
     }
@@ -178,6 +187,10 @@
     VerifyReadArguments(6, true);
 }
 
+TEST_F(OTAPreoptTest, ReadArgumentsV7) {
+    VerifyReadArguments(7, true);
+}
+
 TEST_F(OTAPreoptTest, ReadArgumentsFailToManyArgs) {
     OTAPreoptParameters params;
     std::vector<const char*> args = getArgs(5, true);
diff --git a/data/etc/android.hardware.sensor.assist.xml b/data/etc/android.hardware.sensor.assist.xml
new file mode 100644
index 0000000..c7f9d56
--- /dev/null
+++ b/data/etc/android.hardware.sensor.assist.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2018 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<!-- Feature for devices with an assist gesture sensor. -->
+<permissions>
+    <feature name="android.hardware.sensor.assist" />
+</permissions>
diff --git a/headers/media_plugin/media/drm/DrmAPI.h b/headers/media_plugin/media/drm/DrmAPI.h
index 0a3a356..c44a1f6 100644
--- a/headers/media_plugin/media/drm/DrmAPI.h
+++ b/headers/media_plugin/media/drm/DrmAPI.h
@@ -148,6 +148,9 @@
         enum SecurityLevel {
             // Failure to access security level, an error occurred
             kSecurityLevelUnknown,
+            // The maximum security level of the device. This is the default when
+            // a session is opened if no security level is specified
+            kSecurityLevelMax,
             // Software-based whitebox crypto
             kSecurityLevelSwSecureCrypto,
             // Software-based whitebox crypto and an obfuscated decoder
diff --git a/include/audiomanager/IAudioManager.h b/include/audiomanager/IAudioManager.h
index 067dc5c..d279bbd 100644
--- a/include/audiomanager/IAudioManager.h
+++ b/include/audiomanager/IAudioManager.h
@@ -32,90 +32,10 @@
     // These transaction IDs must be kept in sync with the method order from
     // IAudioService.aidl.
     enum {
-        // transaction IDs for the unsupported methods are commented out
-        /*
-        ADJUSTSUGGESTEDSTREAMVOLUME           = IBinder::FIRST_CALL_TRANSACTION,
-        ADJUSTSTREAMVOLUME                    = IBinder::FIRST_CALL_TRANSACTION + 1,
-        SETSTREAMVOLUME                       = IBinder::FIRST_CALL_TRANSACTION + 2,
-        ISSTREAMMUTE                          = IBinder::FIRST_CALL_TRANSACTION + 3,
-        FORCEREMOTESUBMIXFULLVOLUME           = IBinder::FIRST_CALL_TRANSACTION + 4,
-        ISMASTERMUTE                          = IBinder::FIRST_CALL_TRANSACTION + 5,
-        SETMASTERMUTE                         = IBinder::FIRST_CALL_TRANSACTION + 6,
-        GETSTREAMVOLUME                       = IBinder::FIRST_CALL_TRANSACTION + 7,
-        GETSTREAMMINVOLUME                    = IBinder::FIRST_CALL_TRANSACTION + 8,
-        GETSTREAMMAXVOLUME                    = IBinder::FIRST_CALL_TRANSACTION + 9,
-        GETLASTAUDIBLESTREAMVOLUME            = IBinder::FIRST_CALL_TRANSACTION + 10,
-        SETMICROPHONEMUTE                     = IBinder::FIRST_CALL_TRANSACTION + 11,
-        SETRINGERMODEEXTERNAL                 = IBinder::FIRST_CALL_TRANSACTION + 12,
-        SETRINGERMODEINTERNAL                 = IBinder::FIRST_CALL_TRANSACTION + 13,
-        GETRINGERMODEEXTERNAL                 = IBinder::FIRST_CALL_TRANSACTION + 14,
-        GETRINGERMODEINTERNAL                 = IBinder::FIRST_CALL_TRANSACTION + 15,
-        ISVALIDRINGERMODE                     = IBinder::FIRST_CALL_TRANSACTION + 16,
-        SETVIBRATESETTING                     = IBinder::FIRST_CALL_TRANSACTION + 17,
-        GETVIBRATESETTING                     = IBinder::FIRST_CALL_TRANSACTION + 18,
-        SHOULDVIBRATE                         = IBinder::FIRST_CALL_TRANSACTION + 19,
-        SETMODE                               = IBinder::FIRST_CALL_TRANSACTION + 20,
-        GETMODE                               = IBinder::FIRST_CALL_TRANSACTION + 21,
-        PLAYSOUNDEFFECT                       = IBinder::FIRST_CALL_TRANSACTION + 22,
-        PLAYSOUNDEFFECTVOLUME                 = IBinder::FIRST_CALL_TRANSACTION + 23,
-        LOADSOUNDEFFECTS                      = IBinder::FIRST_CALL_TRANSACTION + 24,
-        UNLOADSOUNDEFFECTS                    = IBinder::FIRST_CALL_TRANSACTION + 25,
-        RELOADAUDIOSETTINGS                   = IBinder::FIRST_CALL_TRANSACTION + 26,
-        AVRCPSUPPORTSABSOLUTEVOLUME           = IBinder::FIRST_CALL_TRANSACTION + 27,
-        SETSPEAKERPHONEON                     = IBinder::FIRST_CALL_TRANSACTION + 28,
-        ISSPEAKERPHONEON                      = IBinder::FIRST_CALL_TRANSACTION + 29,
-        SETBLUETOOTHSCOON                     = IBinder::FIRST_CALL_TRANSACTION + 30,
-        ISBLUETOOTHSCOON                      = IBinder::FIRST_CALL_TRANSACTION + 31,
-        SETBLUETOOTHA2DPON                    = IBinder::FIRST_CALL_TRANSACTION + 32,
-        ISBLUETOOTHA2DPON                     = IBinder::FIRST_CALL_TRANSACTION + 33,
-        REQUESTAUDIOFOCUS                     = IBinder::FIRST_CALL_TRANSACTION + 34,
-        ABANDONAUDIOFOCUS                     = IBinder::FIRST_CALL_TRANSACTION + 35,
-        UNREGISTERAUDIOFOCUSCLIENT            = IBinder::FIRST_CALL_TRANSACTION + 36,
-        GETCURRENTAUDIOFOCUS                  = IBinder::FIRST_CALL_TRANSACTION + 37,
-        STARTBLUETOOTHSCO                     = IBinder::FIRST_CALL_TRANSACTION + 38,
-        STARTBLUETOOTHSCOVIRTUALCALL          = IBinder::FIRST_CALL_TRANSACTION + 39,
-        STOPBLUETOOTHSCO                      = IBinder::FIRST_CALL_TRANSACTION + 40,
-        FORCEVOLUMECONTROLSTREAM              = IBinder::FIRST_CALL_TRANSACTION + 41,
-        SETRINGTONEPLAYER                     = IBinder::FIRST_CALL_TRANSACTION + 42,
-        GETRINGTONEPLAYER                     = IBinder::FIRST_CALL_TRANSACTION + 43,
-        GETUISOUNDSSTREAMTYPE                 = IBinder::FIRST_CALL_TRANSACTION + 44,
-        SETWIREDDEVICECONNECTIONSTATE         = IBinder::FIRST_CALL_TRANSACTION + 45,
-        SETBLUETOOTHA2DPDEVICECONNECTIONSTATE = IBinder::FIRST_CALL_TRANSACTION + 46,
-        HANDLEBLUETOOTHA2DPDEVICECONFIGCHANGE = IBinder::FIRST_CALL_TRANSACTION + 47,
-        STARTWATCHINGROUTES                   = IBinder::FIRST_CALL_TRANSACTION + 48,
-        ISCAMERASOUNDFORCED                   = IBinder::FIRST_CALL_TRANSACTION + 49,
-        SETVOLUMECONTROLLER                   = IBinder::FIRST_CALL_TRANSACTION + 50,
-        NOTIFYVOLUMECONTROLLERVISIBLE         = IBinder::FIRST_CALL_TRANSACTION + 51,
-        ISSTREAMAFFECTEDBYRINGERMODE          = IBinder::FIRST_CALL_TRANSACTION + 52,
-        ISSTREAMAFFECTEDBYMUTE                = IBinder::FIRST_CALL_TRANSACTION + 53,
-        DISABLESAFEMEDIAVOLUME                = IBinder::FIRST_CALL_TRANSACTION + 54,
-        SETHDMISYSTEMAUDIOSUPPORTED           = IBinder::FIRST_CALL_TRANSACTION + 55,
-        ISHDMISYSTEMAUDIOSUPPORTED            = IBinder::FIRST_CALL_TRANSACTION + 56,
-        REGISTERAUDIOPOLICY                   = IBinder::FIRST_CALL_TRANSACTION + 57,
-        UNREGISTERAUDIOPOLICYASYNC            = IBinder::FIRST_CALL_TRANSACTION + 58,
-        SETFOCUSPROPERTIESFORPOLICY           = IBinder::FIRST_CALL_TRANSACTION + 59,
-        SETVOLUMEPOLICY                       = IBinder::FIRST_CALL_TRANSACTION + 60,
-        REGISTERRECORDINGCALLBACK             = IBinder::FIRST_CALL_TRANSACTION + 61,
-        UNREGISTERRECORDINGCALLBACK           = IBinder::FIRST_CALL_TRANSACTION + 62,
-        GETACTIVERECORDINGCONFIGURATIONS      = IBinder::FIRST_CALL_TRANSACTION + 63,
-        REGISTERPLAYBACKCALLBACK              = IBinder::FIRST_CALL_TRANSACTION + 64,
-        UNREGISTERPLAYBACKCALLBACK            = IBinder::FIRST_CALL_TRANSACTION + 65,
-        GETACTIVEPLAYBACKCONFIGURATIONS       = IBinder::FIRST_CALL_TRANSACTION + 66,
-        */
-
-        TRACK_PLAYER                          = IBinder::FIRST_CALL_TRANSACTION + 67,
-        PLAYER_ATTRIBUTES                     = IBinder::FIRST_CALL_TRANSACTION + 68,
-        PLAYER_EVENT                          = IBinder::FIRST_CALL_TRANSACTION + 69,
-        RELEASE_PLAYER                        = IBinder::FIRST_CALL_TRANSACTION + 70,
-
-        /*
-        DISABLE_RINGTONE_SYNC                 = IBinder::FIRST_CALL_TRANSACTION + 71,
-        GET_FOCUS_RAMP_TIME_MS                = IBinder::FIRST_CALL_TRANSACTION + 72,
-        DISPATCH_FOCUS_CHANGE                 = IBinder::FIRST_CALL_TRANSACTION + 73,
-        PLAYER_HAS_OP_PLAY_AUDIO              = IBinder::FIRST_CALL_TRANSACTION + 74,
-        SET_BLUETOOTH_A2DP_DEVICE_CONNECTION_STATE_SUPPRESS_NOISY_INTENT
-                                              = IBinder::FIRST_CALL_TRANSACTION + 75,
-        */
+        TRACK_PLAYER                          = IBinder::FIRST_CALL_TRANSACTION,
+        PLAYER_ATTRIBUTES                     = IBinder::FIRST_CALL_TRANSACTION + 1,
+        PLAYER_EVENT                          = IBinder::FIRST_CALL_TRANSACTION + 2,
+        RELEASE_PLAYER                        = IBinder::FIRST_CALL_TRANSACTION + 3,
     };
 
     DECLARE_META_INTERFACE(AudioManager)
diff --git a/include/input/InputTransport.h b/include/input/InputTransport.h
index 6187528..1ea2c2c 100644
--- a/include/input/InputTransport.h
+++ b/include/input/InputTransport.h
@@ -380,6 +380,18 @@
             }
         }
 
+        void initializeFrom(const History& other) {
+            eventTime = other.eventTime;
+            idBits = other.idBits; // temporary copy
+            for (size_t i = 0; i < other.idBits.count(); i++) {
+                uint32_t id = idBits.clearFirstMarkedBit();
+                int32_t index = other.idToIndex[id];
+                idToIndex[id] = index;
+                pointers[index].copyFrom(other.pointers[index]);
+            }
+            idBits = other.idBits; // final copy
+        }
+
         const PointerCoords& getPointerById(uint32_t id) const {
             return pointers[idToIndex[id]];
         }
@@ -462,7 +474,7 @@
 
     status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
 
-    static bool rewriteMessage(const TouchState& state, InputMessage& msg);
+    static void rewriteMessage(TouchState& state, InputMessage& msg);
     static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
     static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
     static void addSample(MotionEvent* event, const InputMessage* msg);
diff --git a/include/input/KeyCharacterMap.h b/include/input/KeyCharacterMap.h
index 7935927..33d2757 100644
--- a/include/input/KeyCharacterMap.h
+++ b/include/input/KeyCharacterMap.h
@@ -51,6 +51,9 @@
         KEYBOARD_TYPE_PREDICTIVE = 2,
         KEYBOARD_TYPE_ALPHA = 3,
         KEYBOARD_TYPE_FULL = 4,
+        /**
+         * Deprecated. Set 'keyboard.specialFunction' to '1' in the device's IDC file instead.
+         */
         KEYBOARD_TYPE_SPECIAL_FUNCTION = 5,
         KEYBOARD_TYPE_OVERLAY = 6,
     };
diff --git a/libs/binder/ActivityManager.cpp b/libs/binder/ActivityManager.cpp
index 7724bf1..e1cc5da 100644
--- a/libs/binder/ActivityManager.cpp
+++ b/libs/binder/ActivityManager.cpp
@@ -15,6 +15,8 @@
  */
 
 #include <mutex>
+#include <unistd.h>
+
 #include <binder/ActivityManager.h>
 #include <binder/Binder.h>
 #include <binder/IServiceManager.h>
@@ -44,7 +46,7 @@
                 service = NULL;
                 break;
             }
-            sleep(1);
+            usleep(25000);
         } else {
             service = interface_cast<IActivityManager>(binder);
             mService = service;
diff --git a/libs/binder/BufferedTextOutput.cpp b/libs/binder/BufferedTextOutput.cpp
index a2443c0..30e70b0 100644
--- a/libs/binder/BufferedTextOutput.cpp
+++ b/libs/binder/BufferedTextOutput.cpp
@@ -17,11 +17,11 @@
 #include <binder/BufferedTextOutput.h>
 #include <binder/Debug.h>
 
-#include <utils/Atomic.h>
+#include <cutils/atomic.h>
+#include <cutils/threads.h>
 #include <utils/Log.h>
 #include <utils/RefBase.h>
 #include <utils/Vector.h>
-#include <cutils/threads.h>
 
 #include <private/binder/Static.h>
 
diff --git a/libs/binder/ProcessState.cpp b/libs/binder/ProcessState.cpp
index 597fca9..d1c6f84 100644
--- a/libs/binder/ProcessState.cpp
+++ b/libs/binder/ProcessState.cpp
@@ -18,12 +18,12 @@
 
 #include <binder/ProcessState.h>
 
-#include <utils/Atomic.h>
 #include <binder/BpBinder.h>
 #include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <cutils/atomic.h>
 #include <utils/Log.h>
 #include <utils/String8.h>
-#include <binder/IServiceManager.h>
 #include <utils/String8.h>
 #include <utils/threads.h>
 
diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp
index 065d44d..a1a0928 100644
--- a/libs/gui/Android.bp
+++ b/libs/gui/Android.bp
@@ -65,6 +65,9 @@
         // Allow implicit instantiation for templated class function
         "-Wno-undefined-func-template",
 
+        // Allow explicitly marking struct as packed even when unnecessary
+        "-Wno-packed",
+
         "-DDEBUG_ONLY_CODE=0",
     ],
 
@@ -82,6 +85,7 @@
 
     srcs: [
         "BitTube.cpp",
+        "BufferHubConsumer.cpp",
         "BufferHubProducer.cpp",
         "BufferItem.cpp",
         "BufferItemConsumer.cpp",
diff --git a/libs/gui/BufferHubConsumer.cpp b/libs/gui/BufferHubConsumer.cpp
new file mode 100644
index 0000000..b5cdeb2
--- /dev/null
+++ b/libs/gui/BufferHubConsumer.cpp
@@ -0,0 +1,161 @@
+/*
+ * Copyright 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gui/BufferHubConsumer.h>
+
+namespace android {
+
+using namespace dvr;
+
+/* static */
+sp<BufferHubConsumer> BufferHubConsumer::Create(const std::shared_ptr<ConsumerQueue>& queue) {
+    sp<BufferHubConsumer> consumer = new BufferHubConsumer;
+    consumer->mQueue = queue;
+    return consumer;
+}
+
+/* static */ sp<BufferHubConsumer> BufferHubConsumer::Create(ConsumerQueueParcelable parcelable) {
+    if (!parcelable.IsValid()) {
+        ALOGE("BufferHubConsumer::Create: Invalid consumer parcelable.");
+        return nullptr;
+    }
+
+    sp<BufferHubConsumer> consumer = new BufferHubConsumer;
+    consumer->mQueue = ConsumerQueue::Import(parcelable.TakeChannelHandle());
+    return consumer;
+}
+
+status_t BufferHubConsumer::acquireBuffer(BufferItem* /*buffer*/, nsecs_t /*presentWhen*/,
+                                          uint64_t /*maxFrameNumber*/) {
+    ALOGE("BufferHubConsumer::acquireBuffer: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::detachBuffer(int /*slot*/) {
+    ALOGE("BufferHubConsumer::detachBuffer: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::attachBuffer(int* /*outSlot*/, const sp<GraphicBuffer>& /*buffer*/) {
+    ALOGE("BufferHubConsumer::attachBuffer: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::releaseBuffer(int /*buf*/, uint64_t /*frameNumber*/,
+                                          EGLDisplay /*display*/, EGLSyncKHR /*fence*/,
+                                          const sp<Fence>& /*releaseFence*/) {
+    ALOGE("BufferHubConsumer::releaseBuffer: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::consumerConnect(const sp<IConsumerListener>& /*consumer*/,
+                                            bool /*controlledByApp*/) {
+    ALOGE("BufferHubConsumer::consumerConnect: not implemented.");
+
+    // TODO(b/73267953): Make BufferHub honor producer and consumer connection. Returns NO_ERROR to
+    // make IGraphicBufferConsumer_test happy.
+    return NO_ERROR;
+}
+
+status_t BufferHubConsumer::consumerDisconnect() {
+    ALOGE("BufferHubConsumer::consumerDisconnect: not implemented.");
+
+    // TODO(b/73267953): Make BufferHub honor producer and consumer connection. Returns NO_ERROR to
+    // make IGraphicBufferConsumer_test happy.
+    return NO_ERROR;
+}
+
+status_t BufferHubConsumer::getReleasedBuffers(uint64_t* /*slotMask*/) {
+    ALOGE("BufferHubConsumer::getReleasedBuffers: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::setDefaultBufferSize(uint32_t /*w*/, uint32_t /*h*/) {
+    ALOGE("BufferHubConsumer::setDefaultBufferSize: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::setMaxBufferCount(int /*bufferCount*/) {
+    ALOGE("BufferHubConsumer::setMaxBufferCount: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::setMaxAcquiredBufferCount(int /*maxAcquiredBuffers*/) {
+    ALOGE("BufferHubConsumer::setMaxAcquiredBufferCount: not implemented.");
+
+    // TODO(b/73267953): Make BufferHub honor producer and consumer connection. Returns NO_ERROR to
+    // make IGraphicBufferConsumer_test happy.
+    return NO_ERROR;
+}
+
+status_t BufferHubConsumer::setConsumerName(const String8& /*name*/) {
+    ALOGE("BufferHubConsumer::setConsumerName: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::setDefaultBufferFormat(PixelFormat /*defaultFormat*/) {
+    ALOGE("BufferHubConsumer::setDefaultBufferFormat: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::setDefaultBufferDataSpace(android_dataspace /*defaultDataSpace*/) {
+    ALOGE("BufferHubConsumer::setDefaultBufferDataSpace: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::setConsumerUsageBits(uint64_t /*usage*/) {
+    ALOGE("BufferHubConsumer::setConsumerUsageBits: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::setConsumerIsProtected(bool /*isProtected*/) {
+    ALOGE("BufferHubConsumer::setConsumerIsProtected: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::setTransformHint(uint32_t /*hint*/) {
+    ALOGE("BufferHubConsumer::setTransformHint: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::getSidebandStream(sp<NativeHandle>* /*outStream*/) const {
+    ALOGE("BufferHubConsumer::getSidebandStream: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::getOccupancyHistory(
+        bool /*forceFlush*/, std::vector<OccupancyTracker::Segment>* /*outHistory*/) {
+    ALOGE("BufferHubConsumer::getOccupancyHistory: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::discardFreeBuffers() {
+    ALOGE("BufferHubConsumer::discardFreeBuffers: not implemented.");
+    return INVALID_OPERATION;
+}
+
+status_t BufferHubConsumer::dumpState(const String8& /*prefix*/, String8* /*outResult*/) const {
+    ALOGE("BufferHubConsumer::dumpState: not implemented.");
+    return INVALID_OPERATION;
+}
+
+IBinder* BufferHubConsumer::onAsBinder() {
+    ALOGE("BufferHubConsumer::onAsBinder: BufferHubConsumer should never be used as an Binder "
+          "object.");
+    return nullptr;
+}
+
+} // namespace android
diff --git a/libs/gui/BufferHubProducer.cpp b/libs/gui/BufferHubProducer.cpp
index af1f833..70321ca 100644
--- a/libs/gui/BufferHubProducer.cpp
+++ b/libs/gui/BufferHubProducer.cpp
@@ -14,29 +14,18 @@
  * limitations under the License.
  */
 
-#if defined(__clang__)
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Weverything"
-#endif
-
-// The following headers are included without checking every warning.
-// TODO(b/72172820): Remove the workaround once we have enforced -Weverything
-// in these headers and their dependencies.
 #include <dvr/dvr_api.h>
 #include <gui/BufferHubProducer.h>
-
-#if defined(__clang__)
-#pragma clang diagnostic pop
-#endif
-
 #include <inttypes.h>
 #include <log/log.h>
 #include <system/window.h>
 
 namespace android {
 
+using namespace dvr;
+
 /* static */
-sp<BufferHubProducer> BufferHubProducer::Create(const std::shared_ptr<dvr::ProducerQueue>& queue) {
+sp<BufferHubProducer> BufferHubProducer::Create(const std::shared_ptr<ProducerQueue>& queue) {
     if (queue->metadata_size() != sizeof(DvrNativeBufferMetadata)) {
         ALOGE("BufferHubProducer::Create producer's metadata size is different "
               "than the size of DvrNativeBufferMetadata");
@@ -49,14 +38,14 @@
 }
 
 /* static */
-sp<BufferHubProducer> BufferHubProducer::Create(dvr::ProducerQueueParcelable parcelable) {
+sp<BufferHubProducer> BufferHubProducer::Create(ProducerQueueParcelable parcelable) {
     if (!parcelable.IsValid()) {
         ALOGE("BufferHubProducer::Create: Invalid producer parcelable.");
         return nullptr;
     }
 
     sp<BufferHubProducer> producer = new BufferHubProducer;
-    producer->queue_ = dvr::ProducerQueue::Import(parcelable.TakeChannelHandle());
+    producer->queue_ = ProducerQueue::Import(parcelable.TakeChannelHandle());
     return producer;
 }
 
@@ -102,9 +91,9 @@
 
     if (max_dequeued_buffers <= 0 ||
         max_dequeued_buffers >
-                int(dvr::BufferHubQueue::kMaxQueueCapacity - kDefaultUndequeuedBuffers)) {
+                int(BufferHubQueue::kMaxQueueCapacity - kDefaultUndequeuedBuffers)) {
         ALOGE("setMaxDequeuedBufferCount: %d out of range (0, %zu]", max_dequeued_buffers,
-              dvr::BufferHubQueue::kMaxQueueCapacity);
+              BufferHubQueue::kMaxQueueCapacity);
         return BAD_VALUE;
     }
 
@@ -153,7 +142,7 @@
                                           uint32_t height, PixelFormat format, uint64_t usage,
                                           uint64_t* /*outBufferAge*/,
                                           FrameEventHistoryDelta* /* out_timestamps */) {
-    ALOGV("dequeueBuffer: w=%u, h=%u, format=%d, usage=%" PRIu64, width, height, format, usage);
+    ALOGW("dequeueBuffer: w=%u, h=%u, format=%d, usage=%" PRIu64, width, height, format, usage);
 
     status_t ret;
     std::unique_lock<std::mutex> lock(mutex_);
@@ -174,9 +163,9 @@
     }
 
     size_t slot = 0;
-    std::shared_ptr<dvr::BufferProducer> buffer_producer;
+    std::shared_ptr<BufferProducer> buffer_producer;
 
-    for (size_t retry = 0; retry < dvr::BufferHubQueue::kMaxQueueCapacity; retry++) {
+    for (size_t retry = 0; retry < BufferHubQueue::kMaxQueueCapacity; retry++) {
         LocalHandle fence;
         auto buffer_status = queue_->Dequeue(dequeue_timeout_ms_, &slot, &fence);
         if (!buffer_status) return NO_MEMORY;
@@ -225,7 +214,7 @@
 
     buffers_[slot].mBufferState.freeQueued();
     buffers_[slot].mBufferState.dequeue();
-    ALOGV("dequeueBuffer: slot=%zu", slot);
+    ALOGW("dequeueBuffer: slot=%zu", slot);
 
     // TODO(jwcai) Handle fence properly. |BufferHub| has full fence support, we
     // just need to exopose that through |BufferHubQueue| once we need fence.
@@ -590,7 +579,7 @@
     ALOGV(__FUNCTION__);
 
     std::unique_lock<std::mutex> lock(mutex_);
-    dequeue_timeout_ms_ = int(timeout / (1000 * 1000));
+    dequeue_timeout_ms_ = static_cast<int>(timeout / (1000 * 1000));
     return NO_ERROR;
 }
 
@@ -620,7 +609,7 @@
     return NO_ERROR;
 }
 
-status_t BufferHubProducer::TakeAsParcelable(dvr::ProducerQueueParcelable* out_parcelable) {
+status_t BufferHubProducer::TakeAsParcelable(ProducerQueueParcelable* out_parcelable) {
     if (!out_parcelable || out_parcelable->IsValid()) return BAD_VALUE;
 
     if (connected_api_ != kNoConnectedApi) {
@@ -684,7 +673,7 @@
 }
 
 status_t BufferHubProducer::FreeAllBuffers() {
-    for (size_t slot = 0; slot < dvr::BufferHubQueue::kMaxQueueCapacity; slot++) {
+    for (size_t slot = 0; slot < BufferHubQueue::kMaxQueueCapacity; slot++) {
         // Reset in memory objects related the the buffer.
         buffers_[slot].mGraphicBuffer = nullptr;
         buffers_[slot].mBufferState.reset();
@@ -707,4 +696,28 @@
     return NO_ERROR;
 }
 
+status_t BufferHubProducer::exportToParcel(Parcel* parcel) {
+    status_t res = TakeAsParcelable(&pending_producer_parcelable_);
+    if (res != NO_ERROR) return res;
+
+    if (!pending_producer_parcelable_.IsValid()) {
+        ALOGE("BufferHubProducer::exportToParcel: Invalid parcelable object.");
+        return BAD_VALUE;
+    }
+
+    res = parcel->writeUint32(USE_BUFFER_HUB);
+    if (res != NO_ERROR) {
+        ALOGE("BufferHubProducer::exportToParcel: Cannot write magic, res=%d.", res);
+        return res;
+    }
+
+    return pending_producer_parcelable_.writeToParcel(parcel);
+}
+
+IBinder* BufferHubProducer::onAsBinder() {
+    ALOGE("BufferHubProducer::onAsBinder: BufferHubProducer should never be used as an Binder "
+          "object.");
+    return nullptr;
+}
+
 } // namespace android
diff --git a/libs/gui/BufferQueue.cpp b/libs/gui/BufferQueue.cpp
index 4151212..1988690 100644
--- a/libs/gui/BufferQueue.cpp
+++ b/libs/gui/BufferQueue.cpp
@@ -18,6 +18,8 @@
 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
 //#define LOG_NDEBUG 0
 
+#include <gui/BufferHubConsumer.h>
+#include <gui/BufferHubProducer.h>
 #include <gui/BufferQueue.h>
 #include <gui/BufferQueueConsumer.h>
 #include <gui/BufferQueueCore.h>
@@ -101,4 +103,31 @@
     *outConsumer = consumer;
 }
 
+void BufferQueue::createBufferHubQueue(sp<IGraphicBufferProducer>* outProducer,
+                                       sp<IGraphicBufferConsumer>* outConsumer) {
+    LOG_ALWAYS_FATAL_IF(outProducer == NULL, "BufferQueue: outProducer must not be NULL");
+    LOG_ALWAYS_FATAL_IF(outConsumer == NULL, "BufferQueue: outConsumer must not be NULL");
+
+    sp<IGraphicBufferProducer> producer;
+    sp<IGraphicBufferConsumer> consumer;
+
+    dvr::ProducerQueueConfigBuilder configBuilder;
+    std::shared_ptr<dvr::ProducerQueue> producerQueue =
+            dvr::ProducerQueue::Create(configBuilder.SetMetadata<DvrNativeBufferMetadata>().Build(),
+                                       dvr::UsagePolicy{});
+    LOG_ALWAYS_FATAL_IF(producerQueue == NULL, "BufferQueue: failed to create ProducerQueue.");
+
+    std::shared_ptr<dvr::ConsumerQueue> consumerQueue = producerQueue->CreateConsumerQueue();
+    LOG_ALWAYS_FATAL_IF(consumerQueue == NULL, "BufferQueue: failed to create ConsumerQueue.");
+
+    producer = BufferHubProducer::Create(producerQueue);
+    consumer = BufferHubConsumer::Create(consumerQueue);
+
+    LOG_ALWAYS_FATAL_IF(producer == NULL, "BufferQueue: failed to create BufferQueueProducer");
+    LOG_ALWAYS_FATAL_IF(consumer == NULL, "BufferQueue: failed to create BufferQueueConsumer");
+
+    *outProducer = producer;
+    *outConsumer = consumer;
+}
+
 }; // namespace android
diff --git a/libs/gui/BufferQueueProducer.cpp b/libs/gui/BufferQueueProducer.cpp
index 1e8d94c..c8021e4 100644
--- a/libs/gui/BufferQueueProducer.cpp
+++ b/libs/gui/BufferQueueProducer.cpp
@@ -1121,6 +1121,9 @@
         case NATIVE_WINDOW_CONSUMER_IS_PROTECTED:
             value = static_cast<int32_t>(mCore->mConsumerIsProtected);
             break;
+        case NATIVE_WINDOW_MAX_BUFFER_COUNT:
+            value = static_cast<int32_t>(mCore->mMaxBufferCount);
+            break;
         default:
             return BAD_VALUE;
     }
diff --git a/libs/gui/IGraphicBufferProducer.cpp b/libs/gui/IGraphicBufferProducer.cpp
index 7e49024..777a3e5 100644
--- a/libs/gui/IGraphicBufferProducer.cpp
+++ b/libs/gui/IGraphicBufferProducer.cpp
@@ -27,6 +27,7 @@
 #include <binder/Parcel.h>
 #include <binder/IInterface.h>
 
+#include <gui/BufferHubProducer.h>
 #include <gui/BufferQueueDefs.h>
 #include <gui/IGraphicBufferProducer.h>
 #include <gui/IProducerListener.h>
@@ -653,6 +654,75 @@
 
 // ----------------------------------------------------------------------
 
+status_t IGraphicBufferProducer::exportToParcel(Parcel* parcel) {
+    status_t res = OK;
+    res = parcel->writeUint32(USE_BUFFER_QUEUE);
+    if (res != NO_ERROR) {
+        ALOGE("exportToParcel: Cannot write magic, res=%d.", res);
+        return res;
+    }
+
+    return parcel->writeStrongBinder(IInterface::asBinder(this));
+}
+
+/* static */
+status_t IGraphicBufferProducer::exportToParcel(const sp<IGraphicBufferProducer>& producer,
+                                                Parcel* parcel) {
+    if (parcel == nullptr) {
+        ALOGE("exportToParcel: Invalid parcel object.");
+        return BAD_VALUE;
+    }
+
+    if (producer == nullptr) {
+        status_t res = OK;
+        res = parcel->writeUint32(IGraphicBufferProducer::USE_BUFFER_QUEUE);
+        if (res != NO_ERROR) return res;
+        return parcel->writeStrongBinder(nullptr);
+    } else {
+        return producer->exportToParcel(parcel);
+    }
+}
+
+/* static */
+sp<IGraphicBufferProducer> IGraphicBufferProducer::createFromParcel(const Parcel* parcel) {
+    uint32_t outMagic = 0;
+    status_t res = NO_ERROR;
+
+    res = parcel->readUint32(&outMagic);
+    if (res != NO_ERROR) {
+        ALOGE("createFromParcel: Failed to read magic, error=%d.", res);
+        return nullptr;
+    }
+
+    switch (outMagic) {
+        case USE_BUFFER_QUEUE: {
+            sp<IBinder> binder;
+            res = parcel->readNullableStrongBinder(&binder);
+            if (res != NO_ERROR) {
+                ALOGE("createFromParcel: Can't read strong binder.");
+                return nullptr;
+            }
+            return interface_cast<IGraphicBufferProducer>(binder);
+        }
+        case USE_BUFFER_HUB: {
+            ALOGE("createFromParcel: BufferHub not implemented.");
+            dvr::ProducerQueueParcelable producerParcelable;
+            res = producerParcelable.readFromParcel(parcel);
+            if (res != NO_ERROR) {
+                ALOGE("createFromParcel: Failed to read from parcel, error=%d", res);
+                return nullptr;
+            }
+            return BufferHubProducer::Create(std::move(producerParcelable));
+        }
+        default: {
+            ALOGE("createFromParcel: Unexpected mgaic: 0x%x.", outMagic);
+            return nullptr;
+        }
+    }
+}
+
+// ----------------------------------------------------------------------------
+
 status_t BnGraphicBufferProducer::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
diff --git a/libs/gui/LayerState.cpp b/libs/gui/LayerState.cpp
index b5295f2..01acc2d 100644
--- a/libs/gui/LayerState.cpp
+++ b/libs/gui/LayerState.cpp
@@ -231,6 +231,9 @@
         what |= eReparent;
         parentHandleForChild = other.parentHandleForChild;
     }
+    if (other.what & eDestroySurface) {
+        what |= eDestroySurface;
+    }
 }
 
 }; // namespace android
diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp
index c40cad3..b7773c4 100644
--- a/libs/gui/SurfaceComposerClient.cpp
+++ b/libs/gui/SurfaceComposerClient.cpp
@@ -181,7 +181,7 @@
     mAnimation = true;
 }
 
-layer_state_t* SurfaceComposerClient::Transaction::getLayerStateLocked(const sp<SurfaceControl>& sc) {
+layer_state_t* SurfaceComposerClient::Transaction::getLayerState(const sp<SurfaceControl>& sc) {
     ComposerState s;
     s.client = sc->getClient()->mClient;
     s.state.surface = sc->getHandle();
@@ -198,7 +198,7 @@
 
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setPosition(
         const sp<SurfaceControl>& sc, float x, float y) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -221,7 +221,7 @@
 
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setSize(
         const sp<SurfaceControl>& sc, uint32_t w, uint32_t h) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -238,7 +238,7 @@
 
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setLayer(
         const sp<SurfaceControl>& sc, int32_t z) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -250,7 +250,7 @@
 
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setRelativeLayer(const sp<SurfaceControl>& sc, const sp<IBinder>& relativeTo,
         int32_t z) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
     }
@@ -263,7 +263,7 @@
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFlags(
         const sp<SurfaceControl>& sc, uint32_t flags,
         uint32_t mask) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -282,7 +282,7 @@
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setTransparentRegionHint(
         const sp<SurfaceControl>& sc,
         const Region& transparentRegion) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -294,7 +294,7 @@
 
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setAlpha(
         const sp<SurfaceControl>& sc, float alpha) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -306,7 +306,7 @@
 
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setLayerStack(
         const sp<SurfaceControl>& sc, uint32_t layerStack) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -319,7 +319,7 @@
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setMatrix(
         const sp<SurfaceControl>& sc, float dsdx, float dtdx,
         float dtdy, float dsdy) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -336,7 +336,7 @@
 
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setCrop(
         const sp<SurfaceControl>& sc, const Rect& crop) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -347,7 +347,7 @@
 }
 
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFinalCrop(const sp<SurfaceControl>& sc, const Rect& crop) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -360,7 +360,7 @@
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::deferTransactionUntil(
         const sp<SurfaceControl>& sc,
         const sp<IBinder>& handle, uint64_t frameNumber) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -374,7 +374,7 @@
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::deferTransactionUntil(
         const sp<SurfaceControl>& sc,
         const sp<Surface>& barrierSurface, uint64_t frameNumber) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -388,7 +388,7 @@
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::reparentChildren(
         const sp<SurfaceControl>& sc,
         const sp<IBinder>& newParentHandle) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -401,7 +401,7 @@
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::reparent(
         const sp<SurfaceControl>& sc,
         const sp<IBinder>& newParentHandle) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -414,7 +414,7 @@
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setColor(
         const sp<SurfaceControl>& sc,
         const half3& color) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -426,7 +426,7 @@
 
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::detachChildren(
         const sp<SurfaceControl>& sc) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
     }
@@ -436,7 +436,7 @@
 
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setOverrideScalingMode(
         const sp<SurfaceControl>& sc, int32_t overrideScalingMode) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -463,7 +463,7 @@
 
 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setGeometryAppliesWithResize(
         const sp<SurfaceControl>& sc) {
-    layer_state_t* s = getLayerStateLocked(sc);
+    layer_state_t* s = getLayerState(sc);
     if (!s) {
         mStatus = BAD_INDEX;
         return *this;
@@ -472,9 +472,20 @@
     return *this;
 }
 
+SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::destroySurface(
+        const sp<SurfaceControl>& sc) {
+    layer_state_t* s = getLayerState(sc);
+    if (!s) {
+        mStatus = BAD_INDEX;
+        return *this;
+    }
+    s->what |= layer_state_t::eDestroySurface;
+    return *this;
+}
+
 // ---------------------------------------------------------------------------
 
-DisplayState& SurfaceComposerClient::Transaction::getDisplayStateLocked(const sp<IBinder>& token) {
+DisplayState& SurfaceComposerClient::Transaction::getDisplayState(const sp<IBinder>& token) {
     DisplayState s;
     s.token = token;
     ssize_t index = mDisplayStates.indexOf(s);
@@ -499,7 +510,7 @@
             return err;
         }
     }
-    DisplayState& s(getDisplayStateLocked(token));
+    DisplayState& s(getDisplayState(token));
     s.surface = bufferProducer;
     s.what |= DisplayState::eSurfaceChanged;
     return NO_ERROR;
@@ -507,7 +518,7 @@
 
 void SurfaceComposerClient::Transaction::setDisplayLayerStack(const sp<IBinder>& token,
         uint32_t layerStack) {
-    DisplayState& s(getDisplayStateLocked(token));
+    DisplayState& s(getDisplayState(token));
     s.layerStack = layerStack;
     s.what |= DisplayState::eLayerStackChanged;
 }
@@ -516,7 +527,7 @@
         uint32_t orientation,
         const Rect& layerStackRect,
         const Rect& displayRect) {
-    DisplayState& s(getDisplayStateLocked(token));
+    DisplayState& s(getDisplayState(token));
     s.orientation = orientation;
     s.viewport = layerStackRect;
     s.frame = displayRect;
@@ -525,7 +536,7 @@
 }
 
 void SurfaceComposerClient::Transaction::setDisplaySize(const sp<IBinder>& token, uint32_t width, uint32_t height) {
-    DisplayState& s(getDisplayStateLocked(token));
+    DisplayState& s(getDisplayState(token));
     s.width = width;
     s.height = height;
     s.what |= DisplayState::eDisplaySizeChanged;
diff --git a/libs/gui/include/gui/BufferHubConsumer.h b/libs/gui/include/gui/BufferHubConsumer.h
new file mode 100644
index 0000000..d380770
--- /dev/null
+++ b/libs/gui/include/gui/BufferHubConsumer.h
@@ -0,0 +1,112 @@
+/*
+ * Copyright 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_GUI_BUFFERHUBCONSUMER_H_
+#define ANDROID_GUI_BUFFERHUBCONSUMER_H_
+
+#include <gui/IGraphicBufferConsumer.h>
+#include <private/dvr/buffer_hub_queue_client.h>
+#include <private/dvr/buffer_hub_queue_parcelable.h>
+
+namespace android {
+
+class BufferHubConsumer : public IGraphicBufferConsumer {
+public:
+    // Creates a BufferHubConsumer instance by importing an existing producer queue.
+    static sp<BufferHubConsumer> Create(const std::shared_ptr<dvr::ConsumerQueue>& queue);
+
+    // Creates a BufferHubConsumer instance by importing an existing producer
+    // parcelable. Note that this call takes the ownership of the parcelable
+    // object and is guaranteed to succeed if parcelable object is valid.
+    static sp<BufferHubConsumer> Create(dvr::ConsumerQueueParcelable parcelable);
+
+    // See |IGraphicBufferConsumer::acquireBuffer|
+    status_t acquireBuffer(BufferItem* buffer, nsecs_t presentWhen,
+                           uint64_t maxFrameNumber = 0) override;
+
+    // See |IGraphicBufferConsumer::detachBuffer|
+    status_t detachBuffer(int slot) override;
+
+    // See |IGraphicBufferConsumer::attachBuffer|
+    status_t attachBuffer(int* outSlot, const sp<GraphicBuffer>& buffer) override;
+
+    // See |IGraphicBufferConsumer::releaseBuffer|
+    status_t releaseBuffer(int buf, uint64_t frameNumber, EGLDisplay display, EGLSyncKHR fence,
+                           const sp<Fence>& releaseFence) override;
+
+    // See |IGraphicBufferConsumer::consumerConnect|
+    status_t consumerConnect(const sp<IConsumerListener>& consumer, bool controlledByApp) override;
+
+    // See |IGraphicBufferConsumer::consumerDisconnect|
+    status_t consumerDisconnect() override;
+
+    // See |IGraphicBufferConsumer::getReleasedBuffers|
+    status_t getReleasedBuffers(uint64_t* slotMask) override;
+
+    // See |IGraphicBufferConsumer::setDefaultBufferSize|
+    status_t setDefaultBufferSize(uint32_t w, uint32_t h) override;
+
+    // See |IGraphicBufferConsumer::setMaxBufferCount|
+    status_t setMaxBufferCount(int bufferCount) override;
+
+    // See |IGraphicBufferConsumer::setMaxAcquiredBufferCount|
+    status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers) override;
+
+    // See |IGraphicBufferConsumer::setConsumerName|
+    status_t setConsumerName(const String8& name) override;
+
+    // See |IGraphicBufferConsumer::setDefaultBufferFormat|
+    status_t setDefaultBufferFormat(PixelFormat defaultFormat) override;
+
+    // See |IGraphicBufferConsumer::setDefaultBufferDataSpace|
+    status_t setDefaultBufferDataSpace(android_dataspace defaultDataSpace) override;
+
+    // See |IGraphicBufferConsumer::setConsumerUsageBits|
+    status_t setConsumerUsageBits(uint64_t usage) override;
+
+    // See |IGraphicBufferConsumer::setConsumerIsProtected|
+    status_t setConsumerIsProtected(bool isProtected) override;
+
+    // See |IGraphicBufferConsumer::setTransformHint|
+    status_t setTransformHint(uint32_t hint) override;
+
+    // See |IGraphicBufferConsumer::getSidebandStream|
+    status_t getSidebandStream(sp<NativeHandle>* outStream) const override;
+
+    // See |IGraphicBufferConsumer::getOccupancyHistory|
+    status_t getOccupancyHistory(bool forceFlush,
+                                 std::vector<OccupancyTracker::Segment>* outHistory) override;
+
+    // See |IGraphicBufferConsumer::discardFreeBuffers|
+    status_t discardFreeBuffers() override;
+
+    // See |IGraphicBufferConsumer::dumpState|
+    status_t dumpState(const String8& prefix, String8* outResult) const override;
+
+    // BufferHubConsumer provides its own logic to cast to a binder object.
+    IBinder* onAsBinder() override;
+
+private:
+    // Private constructor to force use of |Create|.
+    BufferHubConsumer() = default;
+
+    // Concrete implementation backed by BufferHubBuffer.
+    std::shared_ptr<dvr::ConsumerQueue> mQueue;
+};
+
+} // namespace android
+
+#endif // ANDROID_GUI_BUFFERHUBCONSUMER_H_
diff --git a/libs/gui/include/gui/BufferHubProducer.h b/libs/gui/include/gui/BufferHubProducer.h
index 2ee011b..23c9909 100644
--- a/libs/gui/include/gui/BufferHubProducer.h
+++ b/libs/gui/include/gui/BufferHubProducer.h
@@ -24,7 +24,7 @@
 
 namespace android {
 
-class BufferHubProducer : public BnGraphicBufferProducer {
+class BufferHubProducer : public IGraphicBufferProducer {
 public:
     static constexpr int kNoConnectedApi = -1;
 
@@ -135,6 +135,12 @@
     // invalid parcelable.
     status_t TakeAsParcelable(dvr::ProducerQueueParcelable* out_parcelable);
 
+    IBinder* onAsBinder() override;
+
+protected:
+    // See |IGraphicBufferProducer::exportToParcel|
+    status_t exportToParcel(Parcel* parcel) override;
+
 private:
     using LocalHandle = pdx::LocalHandle;
 
@@ -203,6 +209,9 @@
 
     // A uniqueId used by IGraphicBufferProducer interface.
     const uint64_t unique_id_{genUniqueId()};
+
+    // A pending parcelable object which keeps the bufferhub channel alive.
+    dvr::ProducerQueueParcelable pending_producer_parcelable_;
 };
 
 } // namespace android
diff --git a/libs/gui/include/gui/BufferQueue.h b/libs/gui/include/gui/BufferQueue.h
index ba5cbf7..f175573 100644
--- a/libs/gui/include/gui/BufferQueue.h
+++ b/libs/gui/include/gui/BufferQueue.h
@@ -79,6 +79,10 @@
             sp<IGraphicBufferConsumer>* outConsumer,
             bool consumerIsSurfaceFlinger = false);
 
+    // Creates an IGraphicBufferProducer and IGraphicBufferConsumer pair backed by BufferHub.
+    static void createBufferHubQueue(sp<IGraphicBufferProducer>* outProducer,
+                                     sp<IGraphicBufferConsumer>* outConsumer);
+
     BufferQueue() = delete; // Create through createBufferQueue
 };
 
diff --git a/libs/gui/include/gui/IGraphicBufferProducer.h b/libs/gui/include/gui/IGraphicBufferProducer.h
index 722833e..887654e 100644
--- a/libs/gui/include/gui/IGraphicBufferProducer.h
+++ b/libs/gui/include/gui/IGraphicBufferProducer.h
@@ -73,6 +73,14 @@
         RELEASE_ALL_BUFFERS       = 0x2,
     };
 
+    enum {
+        // A parcelable magic indicates using Binder BufferQueue as transport
+        // backend.
+        USE_BUFFER_QUEUE = 0x62717565, // 'bque'
+        // A parcelable magic indicates using BufferHub as transport backend.
+        USE_BUFFER_HUB = 0x62687562, // 'bhub'
+    };
+
     // requestBuffer requests a new buffer for the given index. The server (i.e.
     // the IGraphicBufferProducer implementation) assigns the newly created
     // buffer to the given slot index, and the client is expected to mirror the
@@ -604,6 +612,24 @@
     // returned by querying the now deprecated
     // NATIVE_WINDOW_CONSUMER_USAGE_BITS attribute.
     virtual status_t getConsumerUsage(uint64_t* outUsage) const = 0;
+
+    // Static method exports any IGraphicBufferProducer object to a parcel. It
+    // handles null producer as well.
+    static status_t exportToParcel(const sp<IGraphicBufferProducer>& producer,
+                                   Parcel* parcel);
+
+    // Factory method that creates a new IBGP instance from the parcel.
+    static sp<IGraphicBufferProducer> createFromParcel(const Parcel* parcel);
+
+protected:
+    // Exports the current producer as a binder parcelable object. Note that the
+    // producer must be disconnected to be exportable. After successful export,
+    // the producer queue can no longer be connected again. Returns NO_ERROR
+    // when the export is successful and writes an implementation defined
+    // parcelable object into the parcel. For traditional Android BufferQueue,
+    // it writes a strong binder object; for BufferHub, it writes a
+    // ProducerQueueParcelable object.
+    virtual status_t exportToParcel(Parcel* parcel);
 };
 
 // ----------------------------------------------------------------------------
diff --git a/libs/gui/include/gui/LayerState.h b/libs/gui/include/gui/LayerState.h
index f3fb82f..788962e 100644
--- a/libs/gui/include/gui/LayerState.h
+++ b/libs/gui/include/gui/LayerState.h
@@ -62,7 +62,8 @@
         eDetachChildren             = 0x00004000,
         eRelativeLayerChanged       = 0x00008000,
         eReparent                   = 0x00010000,
-        eColorChanged               = 0x00020000
+        eColorChanged               = 0x00020000,
+        eDestroySurface             = 0x00040000
     };
 
     layer_state_t()
diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h
index 55b96ac..e5156c6 100644
--- a/libs/gui/include/gui/SurfaceComposerClient.h
+++ b/libs/gui/include/gui/SurfaceComposerClient.h
@@ -136,8 +136,8 @@
 
         int mStatus = NO_ERROR;
 
-        layer_state_t* getLayerStateLocked(const sp<SurfaceControl>& sc);
-        DisplayState& getDisplayStateLocked(const sp<IBinder>& token);
+        layer_state_t* getLayerState(const sp<SurfaceControl>& sc);
+        DisplayState& getDisplayState(const sp<IBinder>& token);
 
     public:
         Transaction() = default;
@@ -229,6 +229,8 @@
         // freezing the total geometry of a surface until a resize is completed.
         Transaction& setGeometryAppliesWithResize(const sp<SurfaceControl>& sc);
 
+        Transaction& destroySurface(const sp<SurfaceControl>& sc);
+
         status_t setDisplaySurface(const sp<IBinder>& token,
                 const sp<IGraphicBufferProducer>& bufferProducer);
 
diff --git a/libs/gui/tests/Android.bp b/libs/gui/tests/Android.bp
index 908959c..01e90e0 100644
--- a/libs/gui/tests/Android.bp
+++ b/libs/gui/tests/Android.bp
@@ -49,3 +49,35 @@
         "libnativewindow"
     ],
 }
+
+// Build a separate binary for each source file to $(TARGET_OUT_DATA_NATIVE_TESTS)/$(LOCAL_MODULE)
+cc_test {
+    name: "libgui_separate_binary_test",
+    test_suites: ["device-tests"],
+
+    clang: true,
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+
+    test_per_src: true,
+    srcs: [
+        "SurfaceParcelable_test.cpp",
+    ],
+
+    shared_libs: [
+        "liblog",
+        "libbinder",
+        "libcutils",
+        "libgui",
+        "libui",
+        "libutils",
+        "libbufferhubqueue",  // TODO(b/70046255): Remove these once BufferHub is integrated into libgui.
+        "libpdx_default_transport",
+    ],
+
+    header_libs: [
+        "libdvr_headers",
+    ],
+}
diff --git a/libs/gui/tests/IGraphicBufferProducer_test.cpp b/libs/gui/tests/IGraphicBufferProducer_test.cpp
index dd23bd4..a35cf11 100644
--- a/libs/gui/tests/IGraphicBufferProducer_test.cpp
+++ b/libs/gui/tests/IGraphicBufferProducer_test.cpp
@@ -42,6 +42,10 @@
 #define TEST_CONTROLLED_BY_APP false
 #define TEST_PRODUCER_USAGE_BITS (0)
 
+#ifndef USE_BUFFER_HUB_AS_BUFFER_QUEUE
+#define USE_BUFFER_HUB_AS_BUFFER_QUEUE 0
+#endif
+
 namespace android {
 
 namespace {
@@ -66,9 +70,15 @@
     const int QUEUE_BUFFER_INPUT_SCALING_MODE = 0;
     const int QUEUE_BUFFER_INPUT_TRANSFORM = 0;
     const sp<Fence> QUEUE_BUFFER_INPUT_FENCE = Fence::NO_FENCE;
+
+    // Enums to control which IGraphicBufferProducer backend to test.
+    enum IGraphicBufferProducerTestCode {
+        USE_BUFFER_QUEUE_PRODUCER = 0,
+        USE_BUFFER_HUB_PRODUCER,
+    };
 }; // namespace anonymous
 
-class IGraphicBufferProducerTest : public ::testing::Test {
+class IGraphicBufferProducerTest : public ::testing::TestWithParam<uint32_t> {
 protected:
 
     IGraphicBufferProducerTest() {}
@@ -81,10 +91,27 @@
 
         mDC = new DummyConsumer;
 
-        BufferQueue::createBufferQueue(&mProducer, &mConsumer);
+        switch (GetParam()) {
+            case USE_BUFFER_QUEUE_PRODUCER: {
+                BufferQueue::createBufferQueue(&mProducer, &mConsumer);
+                break;
+            }
+            case USE_BUFFER_HUB_PRODUCER: {
+                BufferQueue::createBufferHubQueue(&mProducer, &mConsumer);
+                break;
+            }
+            default: {
+                // Should never reach here.
+                LOG_ALWAYS_FATAL("Invalid test params: %u", GetParam());
+                break;
+            }
+        }
 
         // Test check: Can't connect producer if no consumer yet
-        ASSERT_EQ(NO_INIT, TryConnectProducer());
+        if (GetParam() == USE_BUFFER_QUEUE_PRODUCER) {
+            // TODO(b/73267953): Make BufferHub honor producer and consumer connection.
+            ASSERT_EQ(NO_INIT, TryConnectProducer());
+        }
 
         // Must connect consumer before producer connects will succeed.
         ASSERT_OK(mConsumer->consumerConnect(mDC, /*controlledByApp*/false));
@@ -229,7 +256,7 @@
     sp<IGraphicBufferConsumer> mConsumer;
 };
 
-TEST_F(IGraphicBufferProducerTest, ConnectFirst_ReturnsError) {
+TEST_P(IGraphicBufferProducerTest, ConnectFirst_ReturnsError) {
     IGraphicBufferProducer::QueueBufferOutput output;
 
     // NULL output returns BAD_VALUE
@@ -247,7 +274,7 @@
     // TODO: get a token from a dead process somehow
 }
 
-TEST_F(IGraphicBufferProducerTest, ConnectAgain_ReturnsError) {
+TEST_P(IGraphicBufferProducerTest, ConnectAgain_ReturnsError) {
     ASSERT_NO_FATAL_FAILURE(ConnectProducer());
 
     // Can't connect when there is already a producer connected
@@ -259,20 +286,23 @@
 
     ASSERT_OK(mConsumer->consumerDisconnect());
     // Can't connect when IGBP is abandoned
-    EXPECT_EQ(NO_INIT, mProducer->connect(TEST_TOKEN,
-                                          TEST_API,
-                                          TEST_CONTROLLED_BY_APP,
-                                          &output));
+    if (GetParam() == USE_BUFFER_QUEUE_PRODUCER) {
+        // TODO(b/73267953): Make BufferHub honor producer and consumer connection.
+        EXPECT_EQ(NO_INIT, mProducer->connect(TEST_TOKEN,
+                                              TEST_API,
+                                              TEST_CONTROLLED_BY_APP,
+                                              &output));
+    }
 }
 
-TEST_F(IGraphicBufferProducerTest, Disconnect_Succeeds) {
+TEST_P(IGraphicBufferProducerTest, Disconnect_Succeeds) {
     ASSERT_NO_FATAL_FAILURE(ConnectProducer());
 
     ASSERT_OK(mProducer->disconnect(TEST_API));
 }
 
 
-TEST_F(IGraphicBufferProducerTest, Disconnect_ReturnsError) {
+TEST_P(IGraphicBufferProducerTest, Disconnect_ReturnsError) {
     ASSERT_NO_FATAL_FAILURE(ConnectProducer());
 
     // Must disconnect with same API number
@@ -283,7 +313,7 @@
     // TODO: somehow kill mProducer so that this returns DEAD_OBJECT
 }
 
-TEST_F(IGraphicBufferProducerTest, Query_Succeeds) {
+TEST_P(IGraphicBufferProducerTest, Query_Succeeds) {
     ASSERT_NO_FATAL_FAILURE(ConnectProducer());
 
     int32_t value = -1;
@@ -308,7 +338,7 @@
 
 }
 
-TEST_F(IGraphicBufferProducerTest, Query_ReturnsError) {
+TEST_P(IGraphicBufferProducerTest, Query_ReturnsError) {
     ASSERT_NO_FATAL_FAILURE(ConnectProducer());
 
     // One past the end of the last 'query' enum value. Update this if we add more enums.
@@ -334,14 +364,17 @@
     ASSERT_OK(mConsumer->consumerDisconnect());
 
     // BQ was abandoned
-    EXPECT_EQ(NO_INIT, mProducer->query(NATIVE_WINDOW_FORMAT, &value));
+    if (GetParam() == USE_BUFFER_QUEUE_PRODUCER) {
+        // TODO(b/73267953): Make BufferHub honor producer and consumer connection.
+        EXPECT_EQ(NO_INIT, mProducer->query(NATIVE_WINDOW_FORMAT, &value));
+    }
 
     // TODO: other things in window.h that are supported by Surface::query
     // but not by BufferQueue::query
 }
 
 // TODO: queue under more complicated situations not involving just a single buffer
-TEST_F(IGraphicBufferProducerTest, Queue_Succeeds) {
+TEST_P(IGraphicBufferProducerTest, Queue_Succeeds) {
     ASSERT_NO_FATAL_FAILURE(ConnectProducer());
 
     int dequeuedSlot = -1;
@@ -371,16 +404,21 @@
         EXPECT_EQ(DEFAULT_WIDTH, output.width);
         EXPECT_EQ(DEFAULT_HEIGHT, output.height);
         EXPECT_EQ(DEFAULT_TRANSFORM_HINT, output.transformHint);
+
         // Since queueBuffer was called exactly once
-        EXPECT_EQ(1u, output.numPendingBuffers);
-        EXPECT_EQ(2u, output.nextFrameNumber);
+        if (GetParam() == USE_BUFFER_QUEUE_PRODUCER) {
+            // TODO(b/70041889): BufferHubProducer need to support metadata: numPendingBuffers
+            EXPECT_EQ(1u, output.numPendingBuffers);
+            // TODO(b/70041952): BufferHubProducer need to support metadata: nextFrameNumber
+            EXPECT_EQ(2u, output.nextFrameNumber);
+        }
     }
 
     // Buffer was not in the dequeued state
     EXPECT_EQ(BAD_VALUE, mProducer->queueBuffer(dequeuedSlot, input, &output));
 }
 
-TEST_F(IGraphicBufferProducerTest, Queue_ReturnsError) {
+TEST_P(IGraphicBufferProducerTest, Queue_ReturnsError) {
     ASSERT_NO_FATAL_FAILURE(ConnectProducer());
 
     // Invalid slot number
@@ -463,15 +501,16 @@
     ASSERT_OK(mConsumer->consumerDisconnect());
 
     // The buffer queue has been abandoned.
-    {
+    if (GetParam() == USE_BUFFER_QUEUE_PRODUCER) {
         IGraphicBufferProducer::QueueBufferInput input = CreateBufferInput();
         IGraphicBufferProducer::QueueBufferOutput output;
 
+        // TODO(b/73267953): Make BufferHub honor producer and consumer connection.
         EXPECT_EQ(NO_INIT, mProducer->queueBuffer(dequeuedSlot, input, &output));
     }
 }
 
-TEST_F(IGraphicBufferProducerTest, CancelBuffer_DoesntCrash) {
+TEST_P(IGraphicBufferProducerTest, CancelBuffer_DoesntCrash) {
     ASSERT_NO_FATAL_FAILURE(ConnectProducer());
 
     int dequeuedSlot = -1;
@@ -488,7 +527,7 @@
     mProducer->cancelBuffer(dequeuedSlot, dequeuedFence);
 }
 
-TEST_F(IGraphicBufferProducerTest, SetMaxDequeuedBufferCount_Succeeds) {
+TEST_P(IGraphicBufferProducerTest, SetMaxDequeuedBufferCount_Succeeds) {
     ASSERT_NO_FATAL_FAILURE(ConnectProducer());
     int minUndequeuedBuffers;
     ASSERT_OK(mProducer->query(NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
@@ -540,7 +579,7 @@
     ASSERT_OK(mProducer->setMaxDequeuedBufferCount(maxBuffers-1));
 }
 
-TEST_F(IGraphicBufferProducerTest, SetMaxDequeuedBufferCount_Fails) {
+TEST_P(IGraphicBufferProducerTest, SetMaxDequeuedBufferCount_Fails) {
     ASSERT_NO_FATAL_FAILURE(ConnectProducer());
     int minUndequeuedBuffers;
     ASSERT_OK(mProducer->query(NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
@@ -578,12 +617,19 @@
     ASSERT_OK(mConsumer->consumerDisconnect());
 
     // Fail because the buffer queue was abandoned
-    EXPECT_EQ(NO_INIT, mProducer->setMaxDequeuedBufferCount(minBuffers))
-            << "bufferCount: " << minBuffers;
-
+    if (GetParam() == USE_BUFFER_QUEUE_PRODUCER) {
+        // TODO(b/73267953): Make BufferHub honor producer and consumer connection.
+        EXPECT_EQ(NO_INIT, mProducer->setMaxDequeuedBufferCount(minBuffers))
+                << "bufferCount: " << minBuffers;
+    }
 }
 
-TEST_F(IGraphicBufferProducerTest, SetAsyncMode_Succeeds) {
+TEST_P(IGraphicBufferProducerTest, SetAsyncMode_Succeeds) {
+    if (GetParam() == USE_BUFFER_HUB_PRODUCER) {
+        // TODO(b/36724099): Add support for BufferHubProducer::setAsyncMode(true)
+        return;
+    }
+
     ASSERT_OK(mConsumer->setMaxAcquiredBufferCount(1)) << "maxAcquire: " << 1;
     ASSERT_NO_FATAL_FAILURE(ConnectProducer());
     ASSERT_OK(mProducer->setAsyncMode(true)) << "async mode: " << true;
@@ -609,7 +655,7 @@
     }
 }
 
-TEST_F(IGraphicBufferProducerTest, SetAsyncMode_Fails) {
+TEST_P(IGraphicBufferProducerTest, SetAsyncMode_Fails) {
     ASSERT_NO_FATAL_FAILURE(ConnectProducer());
     // Prerequisite to fail out a valid setBufferCount call
     {
@@ -628,11 +674,13 @@
     ASSERT_OK(mConsumer->consumerDisconnect());
 
     // Fail because the buffer queue was abandoned
-    EXPECT_EQ(NO_INIT, mProducer->setAsyncMode(false)) << "asyncMode: "
-            << false;
+    if (GetParam() == USE_BUFFER_QUEUE_PRODUCER) {
+        // TODO(b/36724099): Make BufferHub honor producer and consumer connection.
+        EXPECT_EQ(NO_INIT, mProducer->setAsyncMode(false)) << "asyncMode: " << false;
+    }
 }
 
-TEST_F(IGraphicBufferProducerTest,
+TEST_P(IGraphicBufferProducerTest,
         DisconnectedProducerReturnsError_dequeueBuffer) {
     int slot = -1;
     sp<Fence> fence;
@@ -642,15 +690,18 @@
                                        TEST_PRODUCER_USAGE_BITS, nullptr, nullptr));
 }
 
-TEST_F(IGraphicBufferProducerTest,
+TEST_P(IGraphicBufferProducerTest,
         DisconnectedProducerReturnsError_detachNextBuffer) {
     sp<Fence> fence;
     sp<GraphicBuffer> buffer;
 
-    ASSERT_EQ(NO_INIT, mProducer->detachNextBuffer(&buffer, &fence));
+    if (GetParam() == USE_BUFFER_QUEUE_PRODUCER) {
+        // TODO(b/38137191): Implement BufferHubProducer::detachBuffer
+        ASSERT_EQ(NO_INIT, mProducer->detachNextBuffer(&buffer, &fence));
+    }
 }
 
-TEST_F(IGraphicBufferProducerTest,
+TEST_P(IGraphicBufferProducerTest,
         DisconnectedProducerReturnsError_requestBuffer) {
     ASSERT_NO_FATAL_FAILURE(ConnectProducer());
 
@@ -674,7 +725,7 @@
 }
 
 
-TEST_F(IGraphicBufferProducerTest,
+TEST_P(IGraphicBufferProducerTest,
         DisconnectedProducerReturnsError_detachBuffer) {
     int slot = -1;
     sp<Fence> fence;
@@ -684,10 +735,13 @@
 
     ASSERT_OK(mProducer->disconnect(TEST_API));
 
-    ASSERT_EQ(NO_INIT, mProducer->detachBuffer(slot));
+    if (GetParam() == USE_BUFFER_QUEUE_PRODUCER) {
+        // TODO(b/38137191): Implement BufferHubProducer::detachBuffer
+        ASSERT_EQ(NO_INIT, mProducer->detachBuffer(slot));
+    }
 }
 
-TEST_F(IGraphicBufferProducerTest,
+TEST_P(IGraphicBufferProducerTest,
         DisconnectedProducerReturnsError_queueBuffer) {
     int slot = -1;
     sp<Fence> fence;
@@ -704,7 +758,7 @@
     ASSERT_EQ(NO_INIT, mProducer->queueBuffer(slot, input, &output));
 }
 
-TEST_F(IGraphicBufferProducerTest,
+TEST_P(IGraphicBufferProducerTest,
         DisconnectedProducerReturnsError_cancelBuffer) {
     int slot = -1;
     sp<Fence> fence;
@@ -717,7 +771,7 @@
     ASSERT_EQ(NO_INIT, mProducer->cancelBuffer(slot, fence));
 }
 
-TEST_F(IGraphicBufferProducerTest,
+TEST_P(IGraphicBufferProducerTest,
         DisconnectedProducerReturnsError_attachBuffer) {
     int slot = -1;
     sp<Fence> fence;
@@ -725,11 +779,27 @@
 
     setupDequeueRequestBuffer(&slot, &fence, &buffer);
 
-    ASSERT_OK(mProducer->detachBuffer(slot));
+    if (GetParam() == USE_BUFFER_QUEUE_PRODUCER) {
+        // TODO(b/38137191): Implement BufferHubProducer::detachBuffer
+        ASSERT_OK(mProducer->detachBuffer(slot));
+    }
 
     ASSERT_OK(mProducer->disconnect(TEST_API));
 
-    ASSERT_EQ(NO_INIT, mProducer->attachBuffer(&slot, buffer));
+    if (GetParam() == USE_BUFFER_QUEUE_PRODUCER) {
+        // TODO(b/69981968): Implement BufferHubProducer::attachBuffer
+        ASSERT_EQ(NO_INIT, mProducer->attachBuffer(&slot, buffer));
+    }
 }
 
+#if USE_BUFFER_HUB_AS_BUFFER_QUEUE
+INSTANTIATE_TEST_CASE_P(IGraphicBufferProducerBackends, IGraphicBufferProducerTest,
+                        ::testing::Values(USE_BUFFER_QUEUE_PRODUCER, USE_BUFFER_HUB_PRODUCER));
+#else
+// TODO(b/70046255): Remove the #ifdef here and always tests both backends once BufferHubQueue can
+// pass all existing libgui tests.
+INSTANTIATE_TEST_CASE_P(IGraphicBufferProducerBackends, IGraphicBufferProducerTest,
+                        ::testing::Values(USE_BUFFER_QUEUE_PRODUCER));
+#endif
+
 } // namespace android
diff --git a/libs/gui/tests/SurfaceParcelable_test.cpp b/libs/gui/tests/SurfaceParcelable_test.cpp
new file mode 100644
index 0000000..99a8a7a
--- /dev/null
+++ b/libs/gui/tests/SurfaceParcelable_test.cpp
@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "SurfaceParcelable_test"
+
+#include <gtest/gtest.h>
+
+#include <binder/IServiceManager.h>
+#include <binder/ProcessState.h>
+#include <gui/BufferHubProducer.h>
+#include <gui/BufferQueue.h>
+#include <gui/view/Surface.h>
+#include <utils/Log.h>
+
+namespace android {
+
+static const String16 kTestServiceName = String16("SurfaceParcelableTestService");
+static const String16 kSurfaceName = String16("TEST_SURFACE");
+static const uint32_t kBufferWidth = 100;
+static const uint32_t kBufferHeight = 1;
+static const uint32_t kBufferFormat = HAL_PIXEL_FORMAT_BLOB;
+
+enum SurfaceParcelableTestServiceCode {
+    CREATE_BUFFER_QUEUE_SURFACE = IBinder::FIRST_CALL_TRANSACTION,
+    CREATE_BUFFER_HUB_SURFACE,
+};
+
+class SurfaceParcelableTestService : public BBinder {
+public:
+    SurfaceParcelableTestService() {
+        // BufferQueue
+        BufferQueue::createBufferQueue(&mBufferQueueProducer, &mBufferQueueConsumer);
+
+        // BufferHub
+        dvr::ProducerQueueConfigBuilder configBuilder;
+        mProducerQueue = dvr::ProducerQueue::Create(configBuilder.SetDefaultWidth(kBufferWidth)
+                                                            .SetDefaultHeight(kBufferHeight)
+                                                            .SetDefaultFormat(kBufferFormat)
+                                                            .SetMetadata<DvrNativeBufferMetadata>()
+                                                            .Build(),
+                                                    dvr::UsagePolicy{});
+        mBufferHubProducer = BufferHubProducer::Create(mProducerQueue);
+    }
+
+    ~SurfaceParcelableTestService() = default;
+
+    virtual status_t onTransact(uint32_t code, const Parcel& /*data*/, Parcel* reply,
+                                uint32_t /*flags*/ = 0) {
+        switch (code) {
+            case CREATE_BUFFER_QUEUE_SURFACE: {
+                view::Surface surfaceShim;
+                surfaceShim.name = kSurfaceName;
+                surfaceShim.graphicBufferProducer = mBufferQueueProducer;
+                return surfaceShim.writeToParcel(reply);
+            }
+            case CREATE_BUFFER_HUB_SURFACE: {
+                view::Surface surfaceShim;
+                surfaceShim.name = kSurfaceName;
+                surfaceShim.graphicBufferProducer = mBufferHubProducer;
+                return surfaceShim.writeToParcel(reply);
+            }
+            default:
+                return UNKNOWN_TRANSACTION;
+        };
+    }
+
+protected:
+    sp<IGraphicBufferProducer> mBufferQueueProducer;
+    sp<IGraphicBufferConsumer> mBufferQueueConsumer;
+
+    std::shared_ptr<dvr::ProducerQueue> mProducerQueue;
+    sp<IGraphicBufferProducer> mBufferHubProducer;
+};
+
+static int runBinderServer() {
+    ProcessState::self()->startThreadPool();
+
+    sp<IServiceManager> sm = defaultServiceManager();
+    sp<SurfaceParcelableTestService> service = new SurfaceParcelableTestService;
+    sm->addService(kTestServiceName, service, false);
+
+    ALOGI("Binder server running...");
+
+    while (true) {
+        int stat, retval;
+        retval = wait(&stat);
+        if (retval == -1 && errno == ECHILD) {
+            break;
+        }
+    }
+
+    ALOGI("Binder server exiting...");
+    return 0;
+}
+
+class SurfaceParcelableTest : public ::testing::TestWithParam<uint32_t> {
+protected:
+    virtual void SetUp() {
+        mService = defaultServiceManager()->getService(kTestServiceName);
+        if (mService == nullptr) {
+            ALOGE("Failed to connect to the test service.");
+            return;
+        }
+
+        ALOGI("Binder service is ready for client.");
+    }
+
+    status_t GetSurface(view::Surface* surfaceShim) {
+        ALOGI("...Test: %d", GetParam());
+
+        uint32_t opCode = GetParam();
+        Parcel data;
+        Parcel reply;
+        status_t error = mService->transact(opCode, data, &reply);
+        if (error != NO_ERROR) {
+            ALOGE("Failed to get surface over binder, error=%d.", error);
+            return error;
+        }
+
+        error = surfaceShim->readFromParcel(&reply);
+        if (error != NO_ERROR) {
+            ALOGE("Failed to get surface from parcel, error=%d.", error);
+            return error;
+        }
+
+        return NO_ERROR;
+    }
+
+private:
+    sp<IBinder> mService;
+};
+
+TEST_P(SurfaceParcelableTest, SendOverBinder) {
+    view::Surface surfaceShim;
+    EXPECT_EQ(GetSurface(&surfaceShim), NO_ERROR);
+    EXPECT_EQ(surfaceShim.name, kSurfaceName);
+    EXPECT_FALSE(surfaceShim.graphicBufferProducer == nullptr);
+}
+
+INSTANTIATE_TEST_CASE_P(SurfaceBackends, SurfaceParcelableTest,
+                        ::testing::Values(CREATE_BUFFER_QUEUE_SURFACE, CREATE_BUFFER_HUB_SURFACE));
+
+} // namespace android
+
+int main(int argc, char** argv) {
+    pid_t pid = fork();
+    if (pid == 0) {
+        android::ProcessState::self()->startThreadPool();
+        ::testing::InitGoogleTest(&argc, argv);
+        return RUN_ALL_TESTS();
+
+    } else {
+        ALOGI("Test process pid: %d.", pid);
+        return android::runBinderServer();
+    }
+}
diff --git a/libs/gui/view/Surface.cpp b/libs/gui/view/Surface.cpp
index 5ed3d3b..d64dfd5 100644
--- a/libs/gui/view/Surface.cpp
+++ b/libs/gui/view/Surface.cpp
@@ -45,10 +45,7 @@
         if (res != OK) return res;
     }
 
-    res = parcel->writeStrongBinder(
-            IGraphicBufferProducer::asBinder(graphicBufferProducer));
-
-    return res;
+    return IGraphicBufferProducer::exportToParcel(graphicBufferProducer, parcel);
 }
 
 status_t Surface::readFromParcel(const Parcel* parcel) {
@@ -70,16 +67,7 @@
         }
     }
 
-    sp<IBinder> binder;
-
-    res = parcel->readNullableStrongBinder(&binder);
-    if (res != OK) {
-        ALOGE("%s: Can't read strong binder", __FUNCTION__);
-        return res;
-    }
-
-    graphicBufferProducer = interface_cast<IGraphicBufferProducer>(binder);
-
+    graphicBufferProducer = IGraphicBufferProducer::createFromParcel(parcel);
     return OK;
 }
 
diff --git a/libs/hwc2on1adapter/Android.bp b/libs/hwc2on1adapter/Android.bp
deleted file mode 100644
index 420a1f6..0000000
--- a/libs/hwc2on1adapter/Android.bp
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright 2010 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.
-
-cc_library_shared {
-    name: "libhwc2on1adapter",
-    vendor: true,
-
-    clang: true,
-    cflags: [
-        "-Wall",
-        "-Werror",
-        "-Wno-user-defined-warnings",
-    ],
-    cppflags: [
-        "-Weverything",
-        "-Wunused",
-        "-Wunreachable-code",
-
-        // The static constructors and destructors in this library have not been noted to
-        // introduce significant overheads
-        "-Wno-exit-time-destructors",
-        "-Wno-global-constructors",
-
-        // We only care about compiling as C++14
-        "-Wno-c++98-compat-pedantic",
-
-        // android/sensors.h uses nested anonymous unions and anonymous structs
-        "-Wno-nested-anon-types",
-        "-Wno-gnu-anonymous-struct",
-
-        // Don't warn about struct padding
-        "-Wno-padded",
-
-        // hwcomposer2.h features switch covering all cases.
-        "-Wno-covered-switch-default",
-
-        // hwcomposer.h features zero size array.
-        "-Wno-zero-length-array",
-
-        // Disabling warning specific to hwc2on1adapter code
-        "-Wno-double-promotion",
-        "-Wno-sign-conversion",
-        "-Wno-switch-enum",
-        "-Wno-float-equal",
-        "-Wno-shorten-64-to-32",
-        "-Wno-sign-compare",
-        "-Wno-missing-prototypes",
-    ],
-
-    srcs: [
-        "HWC2On1Adapter.cpp",
-        "MiniFence.cpp",
-    ],
-
-    shared_libs: [
-        "libutils",
-        "libcutils",
-        "liblog",
-        "libhardware",
-    ],
-
-    export_include_dirs: ["include"],
-
-    export_shared_lib_headers: ["libutils"],
-}
diff --git a/libs/hwc2on1adapter/CleanSpec.mk b/libs/hwc2on1adapter/CleanSpec.mk
deleted file mode 100644
index 7fc2216..0000000
--- a/libs/hwc2on1adapter/CleanSpec.mk
+++ /dev/null
@@ -1,52 +0,0 @@
-# Copyright (C) 2017 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-# If you don't need to do a full clean build but would like to touch
-# a file or delete some intermediate files, add a clean step to the end
-# of the list.  These steps will only be run once, if they haven't been
-# run before.
-#
-# E.g.:
-#     $(call add-clean-step, touch -c external/sqlite/sqlite3.h)
-#     $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libz_intermediates)
-#
-# Always use "touch -c" and "rm -f" or "rm -rf" to gracefully deal with
-# files that are missing or have been moved.
-#
-# Use $(PRODUCT_OUT) to get to the "out/target/product/blah/" directory.
-# Use $(OUT_DIR) to refer to the "out" directory.
-#
-# If you need to re-do something that's already mentioned, just copy
-# the command and add it to the bottom of the list.  E.g., if a change
-# that you made last week required touching a file and a change you
-# made today requires touching the same file, just copy the old
-# touch step and add it to the end of the list.
-#
-# ************************************************
-# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
-# ************************************************
-
-# For example:
-#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/AndroidTests_intermediates)
-#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/core_intermediates)
-#$(call add-clean-step, find $(OUT_DIR) -type f -name "IGTalkSession*" -print0 | xargs -0 rm -f)
-#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*)
-
-# ************************************************
-# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
-# ************************************************
-$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libhwc2on1adapter_intermediates)
-$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib/libhwc2on1adapter.so)
-$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib64/libhwc2on1adapter.so)
diff --git a/libs/hwc2on1adapter/HWC2On1Adapter.cpp b/libs/hwc2on1adapter/HWC2On1Adapter.cpp
deleted file mode 100644
index 77f06bb..0000000
--- a/libs/hwc2on1adapter/HWC2On1Adapter.cpp
+++ /dev/null
@@ -1,2637 +0,0 @@
-/*
- * Copyright 2015 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 "hwc2on1adapter/HWC2On1Adapter.h"
-
-//#define LOG_NDEBUG 0
-
-#undef LOG_TAG
-#define LOG_TAG "HWC2On1Adapter"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
-
-
-#include <inttypes.h>
-
-#include <chrono>
-#include <cstdlib>
-#include <sstream>
-
-#include <hardware/hwcomposer.h>
-#include <log/log.h>
-#include <utils/Trace.h>
-
-using namespace std::chrono_literals;
-
-static uint8_t getMinorVersion(struct hwc_composer_device_1* device)
-{
-    auto version = device->common.version & HARDWARE_API_VERSION_2_MAJ_MIN_MASK;
-    return (version >> 16) & 0xF;
-}
-
-template <typename PFN, typename T>
-static hwc2_function_pointer_t asFP(T function)
-{
-    static_assert(std::is_same<PFN, T>::value, "Incompatible function pointer");
-    return reinterpret_cast<hwc2_function_pointer_t>(function);
-}
-
-using namespace HWC2;
-
-static constexpr Attribute ColorMode = static_cast<Attribute>(6);
-
-namespace android {
-
-class HWC2On1Adapter::Callbacks : public hwc_procs_t {
-    public:
-        explicit Callbacks(HWC2On1Adapter& adapter) : mAdapter(adapter) {
-            invalidate = &invalidateHook;
-            vsync = &vsyncHook;
-            hotplug = &hotplugHook;
-        }
-
-        static void invalidateHook(const hwc_procs_t* procs) {
-            auto callbacks = static_cast<const Callbacks*>(procs);
-            callbacks->mAdapter.hwc1Invalidate();
-        }
-
-        static void vsyncHook(const hwc_procs_t* procs, int display,
-                int64_t timestamp) {
-            auto callbacks = static_cast<const Callbacks*>(procs);
-            callbacks->mAdapter.hwc1Vsync(display, timestamp);
-        }
-
-        static void hotplugHook(const hwc_procs_t* procs, int display,
-                int connected) {
-            auto callbacks = static_cast<const Callbacks*>(procs);
-            callbacks->mAdapter.hwc1Hotplug(display, connected);
-        }
-
-    private:
-        HWC2On1Adapter& mAdapter;
-};
-
-static int closeHook(hw_device_t* /*device*/)
-{
-    // Do nothing, since the real work is done in the class destructor, but we
-    // need to provide a valid function pointer for hwc2_close to call
-    return 0;
-}
-
-HWC2On1Adapter::HWC2On1Adapter(hwc_composer_device_1_t* hwc1Device)
-  : mDumpString(),
-    mHwc1Device(hwc1Device),
-    mHwc1MinorVersion(getMinorVersion(hwc1Device)),
-    mHwc1SupportsVirtualDisplays(false),
-    mHwc1SupportsBackgroundColor(false),
-    mHwc1Callbacks(std::make_unique<Callbacks>(*this)),
-    mCapabilities(),
-    mLayers(),
-    mHwc1VirtualDisplay(),
-    mStateMutex(),
-    mCallbacks(),
-    mHasPendingInvalidate(false),
-    mPendingVsyncs(),
-    mPendingHotplugs(),
-    mDisplays(),
-    mHwc1DisplayMap()
-{
-    common.close = closeHook;
-    getCapabilities = getCapabilitiesHook;
-    getFunction = getFunctionHook;
-    populateCapabilities();
-    populatePrimary();
-    mHwc1Device->registerProcs(mHwc1Device,
-            static_cast<const hwc_procs_t*>(mHwc1Callbacks.get()));
-}
-
-HWC2On1Adapter::~HWC2On1Adapter() {
-    hwc_close_1(mHwc1Device);
-}
-
-void HWC2On1Adapter::doGetCapabilities(uint32_t* outCount,
-        int32_t* outCapabilities) {
-    if (outCapabilities == nullptr) {
-        *outCount = mCapabilities.size();
-        return;
-    }
-
-    auto capabilityIter = mCapabilities.cbegin();
-    for (size_t written = 0; written < *outCount; ++written) {
-        if (capabilityIter == mCapabilities.cend()) {
-            return;
-        }
-        outCapabilities[written] = static_cast<int32_t>(*capabilityIter);
-        ++capabilityIter;
-    }
-}
-
-hwc2_function_pointer_t HWC2On1Adapter::doGetFunction(
-        FunctionDescriptor descriptor) {
-    switch (descriptor) {
-        // Device functions
-        case FunctionDescriptor::CreateVirtualDisplay:
-            return asFP<HWC2_PFN_CREATE_VIRTUAL_DISPLAY>(
-                    createVirtualDisplayHook);
-        case FunctionDescriptor::DestroyVirtualDisplay:
-            return asFP<HWC2_PFN_DESTROY_VIRTUAL_DISPLAY>(
-                    destroyVirtualDisplayHook);
-        case FunctionDescriptor::Dump:
-            return asFP<HWC2_PFN_DUMP>(dumpHook);
-        case FunctionDescriptor::GetMaxVirtualDisplayCount:
-            return asFP<HWC2_PFN_GET_MAX_VIRTUAL_DISPLAY_COUNT>(
-                    getMaxVirtualDisplayCountHook);
-        case FunctionDescriptor::RegisterCallback:
-            return asFP<HWC2_PFN_REGISTER_CALLBACK>(registerCallbackHook);
-
-        // Display functions
-        case FunctionDescriptor::AcceptDisplayChanges:
-            return asFP<HWC2_PFN_ACCEPT_DISPLAY_CHANGES>(
-                    displayHook<decltype(&Display::acceptChanges),
-                    &Display::acceptChanges>);
-        case FunctionDescriptor::CreateLayer:
-            return asFP<HWC2_PFN_CREATE_LAYER>(
-                    displayHook<decltype(&Display::createLayer),
-                    &Display::createLayer, hwc2_layer_t*>);
-        case FunctionDescriptor::DestroyLayer:
-            return asFP<HWC2_PFN_DESTROY_LAYER>(
-                    displayHook<decltype(&Display::destroyLayer),
-                    &Display::destroyLayer, hwc2_layer_t>);
-        case FunctionDescriptor::GetActiveConfig:
-            return asFP<HWC2_PFN_GET_ACTIVE_CONFIG>(
-                    displayHook<decltype(&Display::getActiveConfig),
-                    &Display::getActiveConfig, hwc2_config_t*>);
-        case FunctionDescriptor::GetChangedCompositionTypes:
-            return asFP<HWC2_PFN_GET_CHANGED_COMPOSITION_TYPES>(
-                    displayHook<decltype(&Display::getChangedCompositionTypes),
-                    &Display::getChangedCompositionTypes, uint32_t*,
-                    hwc2_layer_t*, int32_t*>);
-        case FunctionDescriptor::GetColorModes:
-            return asFP<HWC2_PFN_GET_COLOR_MODES>(
-                    displayHook<decltype(&Display::getColorModes),
-                    &Display::getColorModes, uint32_t*, int32_t*>);
-        case FunctionDescriptor::GetDisplayAttribute:
-            return asFP<HWC2_PFN_GET_DISPLAY_ATTRIBUTE>(
-                    getDisplayAttributeHook);
-        case FunctionDescriptor::GetDisplayConfigs:
-            return asFP<HWC2_PFN_GET_DISPLAY_CONFIGS>(
-                    displayHook<decltype(&Display::getConfigs),
-                    &Display::getConfigs, uint32_t*, hwc2_config_t*>);
-        case FunctionDescriptor::GetDisplayName:
-            return asFP<HWC2_PFN_GET_DISPLAY_NAME>(
-                    displayHook<decltype(&Display::getName),
-                    &Display::getName, uint32_t*, char*>);
-        case FunctionDescriptor::GetDisplayRequests:
-            return asFP<HWC2_PFN_GET_DISPLAY_REQUESTS>(
-                    displayHook<decltype(&Display::getRequests),
-                    &Display::getRequests, int32_t*, uint32_t*, hwc2_layer_t*,
-                    int32_t*>);
-        case FunctionDescriptor::GetDisplayType:
-            return asFP<HWC2_PFN_GET_DISPLAY_TYPE>(
-                    displayHook<decltype(&Display::getType),
-                    &Display::getType, int32_t*>);
-        case FunctionDescriptor::GetDozeSupport:
-            return asFP<HWC2_PFN_GET_DOZE_SUPPORT>(
-                    displayHook<decltype(&Display::getDozeSupport),
-                    &Display::getDozeSupport, int32_t*>);
-        case FunctionDescriptor::GetHdrCapabilities:
-            return asFP<HWC2_PFN_GET_HDR_CAPABILITIES>(
-                    displayHook<decltype(&Display::getHdrCapabilities),
-                    &Display::getHdrCapabilities, uint32_t*, int32_t*, float*,
-                    float*, float*>);
-        case FunctionDescriptor::GetReleaseFences:
-            return asFP<HWC2_PFN_GET_RELEASE_FENCES>(
-                    displayHook<decltype(&Display::getReleaseFences),
-                    &Display::getReleaseFences, uint32_t*, hwc2_layer_t*,
-                    int32_t*>);
-        case FunctionDescriptor::PresentDisplay:
-            return asFP<HWC2_PFN_PRESENT_DISPLAY>(
-                    displayHook<decltype(&Display::present),
-                    &Display::present, int32_t*>);
-        case FunctionDescriptor::SetActiveConfig:
-            return asFP<HWC2_PFN_SET_ACTIVE_CONFIG>(
-                    displayHook<decltype(&Display::setActiveConfig),
-                    &Display::setActiveConfig, hwc2_config_t>);
-        case FunctionDescriptor::SetClientTarget:
-            return asFP<HWC2_PFN_SET_CLIENT_TARGET>(
-                    displayHook<decltype(&Display::setClientTarget),
-                    &Display::setClientTarget, buffer_handle_t, int32_t,
-                    int32_t, hwc_region_t>);
-        case FunctionDescriptor::SetColorMode:
-            return asFP<HWC2_PFN_SET_COLOR_MODE>(setColorModeHook);
-        case FunctionDescriptor::SetColorTransform:
-            return asFP<HWC2_PFN_SET_COLOR_TRANSFORM>(setColorTransformHook);
-        case FunctionDescriptor::SetOutputBuffer:
-            return asFP<HWC2_PFN_SET_OUTPUT_BUFFER>(
-                    displayHook<decltype(&Display::setOutputBuffer),
-                    &Display::setOutputBuffer, buffer_handle_t, int32_t>);
-        case FunctionDescriptor::SetPowerMode:
-            return asFP<HWC2_PFN_SET_POWER_MODE>(setPowerModeHook);
-        case FunctionDescriptor::SetVsyncEnabled:
-            return asFP<HWC2_PFN_SET_VSYNC_ENABLED>(setVsyncEnabledHook);
-        case FunctionDescriptor::ValidateDisplay:
-            return asFP<HWC2_PFN_VALIDATE_DISPLAY>(
-                    displayHook<decltype(&Display::validate),
-                    &Display::validate, uint32_t*, uint32_t*>);
-        case FunctionDescriptor::GetClientTargetSupport:
-            return asFP<HWC2_PFN_GET_CLIENT_TARGET_SUPPORT>(
-                    displayHook<decltype(&Display::getClientTargetSupport),
-                    &Display::getClientTargetSupport, uint32_t, uint32_t,
-                                                      int32_t, int32_t>);
-
-        // Layer functions
-        case FunctionDescriptor::SetCursorPosition:
-            return asFP<HWC2_PFN_SET_CURSOR_POSITION>(
-                    layerHook<decltype(&Layer::setCursorPosition),
-                    &Layer::setCursorPosition, int32_t, int32_t>);
-        case FunctionDescriptor::SetLayerBuffer:
-            return asFP<HWC2_PFN_SET_LAYER_BUFFER>(
-                    layerHook<decltype(&Layer::setBuffer), &Layer::setBuffer,
-                    buffer_handle_t, int32_t>);
-        case FunctionDescriptor::SetLayerSurfaceDamage:
-            return asFP<HWC2_PFN_SET_LAYER_SURFACE_DAMAGE>(
-                    layerHook<decltype(&Layer::setSurfaceDamage),
-                    &Layer::setSurfaceDamage, hwc_region_t>);
-
-        // Layer state functions
-        case FunctionDescriptor::SetLayerBlendMode:
-            return asFP<HWC2_PFN_SET_LAYER_BLEND_MODE>(
-                    setLayerBlendModeHook);
-        case FunctionDescriptor::SetLayerColor:
-            return asFP<HWC2_PFN_SET_LAYER_COLOR>(
-                    layerHook<decltype(&Layer::setColor), &Layer::setColor,
-                    hwc_color_t>);
-        case FunctionDescriptor::SetLayerCompositionType:
-            return asFP<HWC2_PFN_SET_LAYER_COMPOSITION_TYPE>(
-                    setLayerCompositionTypeHook);
-        case FunctionDescriptor::SetLayerDataspace:
-            return asFP<HWC2_PFN_SET_LAYER_DATASPACE>(setLayerDataspaceHook);
-        case FunctionDescriptor::SetLayerDisplayFrame:
-            return asFP<HWC2_PFN_SET_LAYER_DISPLAY_FRAME>(
-                    layerHook<decltype(&Layer::setDisplayFrame),
-                    &Layer::setDisplayFrame, hwc_rect_t>);
-        case FunctionDescriptor::SetLayerPlaneAlpha:
-            return asFP<HWC2_PFN_SET_LAYER_PLANE_ALPHA>(
-                    layerHook<decltype(&Layer::setPlaneAlpha),
-                    &Layer::setPlaneAlpha, float>);
-        case FunctionDescriptor::SetLayerSidebandStream:
-            return asFP<HWC2_PFN_SET_LAYER_SIDEBAND_STREAM>(
-                    layerHook<decltype(&Layer::setSidebandStream),
-                    &Layer::setSidebandStream, const native_handle_t*>);
-        case FunctionDescriptor::SetLayerSourceCrop:
-            return asFP<HWC2_PFN_SET_LAYER_SOURCE_CROP>(
-                    layerHook<decltype(&Layer::setSourceCrop),
-                    &Layer::setSourceCrop, hwc_frect_t>);
-        case FunctionDescriptor::SetLayerTransform:
-            return asFP<HWC2_PFN_SET_LAYER_TRANSFORM>(setLayerTransformHook);
-        case FunctionDescriptor::SetLayerVisibleRegion:
-            return asFP<HWC2_PFN_SET_LAYER_VISIBLE_REGION>(
-                    layerHook<decltype(&Layer::setVisibleRegion),
-                    &Layer::setVisibleRegion, hwc_region_t>);
-        case FunctionDescriptor::SetLayerZOrder:
-            return asFP<HWC2_PFN_SET_LAYER_Z_ORDER>(setLayerZOrderHook);
-
-        default:
-            ALOGE("doGetFunction: Unknown function descriptor: %d (%s)",
-                    static_cast<int32_t>(descriptor),
-                    to_string(descriptor).c_str());
-            return nullptr;
-    }
-}
-
-// Device functions
-
-Error HWC2On1Adapter::createVirtualDisplay(uint32_t width,
-        uint32_t height, hwc2_display_t* outDisplay) {
-    std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
-
-    if (mHwc1VirtualDisplay) {
-        // We have already allocated our only HWC1 virtual display
-        ALOGE("createVirtualDisplay: HWC1 virtual display already allocated");
-        return Error::NoResources;
-    }
-
-    mHwc1VirtualDisplay = std::make_shared<HWC2On1Adapter::Display>(*this,
-            HWC2::DisplayType::Virtual);
-    mHwc1VirtualDisplay->populateConfigs(width, height);
-    const auto displayId = mHwc1VirtualDisplay->getId();
-    mHwc1DisplayMap[HWC_DISPLAY_VIRTUAL] = displayId;
-    mHwc1VirtualDisplay->setHwc1Id(HWC_DISPLAY_VIRTUAL);
-    mDisplays.emplace(displayId, mHwc1VirtualDisplay);
-    *outDisplay = displayId;
-
-    return Error::None;
-}
-
-Error HWC2On1Adapter::destroyVirtualDisplay(hwc2_display_t displayId) {
-    std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
-
-    if (!mHwc1VirtualDisplay || (mHwc1VirtualDisplay->getId() != displayId)) {
-        return Error::BadDisplay;
-    }
-
-    mHwc1VirtualDisplay.reset();
-    mHwc1DisplayMap.erase(HWC_DISPLAY_VIRTUAL);
-    mDisplays.erase(displayId);
-
-    return Error::None;
-}
-
-void HWC2On1Adapter::dump(uint32_t* outSize, char* outBuffer) {
-    if (outBuffer != nullptr) {
-        auto copiedBytes = mDumpString.copy(outBuffer, *outSize);
-        *outSize = static_cast<uint32_t>(copiedBytes);
-        return;
-    }
-
-    std::stringstream output;
-
-    output << "-- HWC2On1Adapter --\n";
-
-    output << "Adapting to a HWC 1." << static_cast<int>(mHwc1MinorVersion) <<
-            " device\n";
-
-    // Attempt to acquire the lock for 1 second, but proceed without the lock
-    // after that, so we can still get some information if we're deadlocked
-    std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex,
-            std::defer_lock);
-    lock.try_lock_for(1s);
-
-    if (mCapabilities.empty()) {
-        output << "Capabilities: None\n";
-    } else {
-        output << "Capabilities:\n";
-        for (auto capability : mCapabilities) {
-            output << "  " << to_string(capability) << '\n';
-        }
-    }
-
-    output << "Displays:\n";
-    for (const auto& element : mDisplays) {
-        const auto& display = element.second;
-        output << display->dump();
-    }
-    output << '\n';
-
-    // Release the lock before calling into HWC1, and since we no longer require
-    // mutual exclusion to access mCapabilities or mDisplays
-    lock.unlock();
-
-    if (mHwc1Device->dump) {
-        output << "HWC1 dump:\n";
-        std::vector<char> hwc1Dump(4096);
-        // Call with size - 1 to preserve a null character at the end
-        mHwc1Device->dump(mHwc1Device, hwc1Dump.data(),
-                static_cast<int>(hwc1Dump.size() - 1));
-        output << hwc1Dump.data();
-    }
-
-    mDumpString = output.str();
-    *outSize = static_cast<uint32_t>(mDumpString.size());
-}
-
-uint32_t HWC2On1Adapter::getMaxVirtualDisplayCount() {
-    return mHwc1SupportsVirtualDisplays ? 1 : 0;
-}
-
-static bool isValid(Callback descriptor) {
-    switch (descriptor) {
-        case Callback::Hotplug: // Fall-through
-        case Callback::Refresh: // Fall-through
-        case Callback::Vsync: return true;
-        default: return false;
-    }
-}
-
-Error HWC2On1Adapter::registerCallback(Callback descriptor,
-        hwc2_callback_data_t callbackData, hwc2_function_pointer_t pointer) {
-    if (!isValid(descriptor)) {
-        return Error::BadParameter;
-    }
-
-    ALOGV("registerCallback(%s, %p, %p)", to_string(descriptor).c_str(),
-            callbackData, pointer);
-
-    std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
-
-    if (pointer != nullptr) {
-        mCallbacks[descriptor] = {callbackData, pointer};
-    } else {
-        ALOGI("unregisterCallback(%s)", to_string(descriptor).c_str());
-        mCallbacks.erase(descriptor);
-        return Error::None;
-    }
-
-    bool hasPendingInvalidate = false;
-    std::vector<hwc2_display_t> displayIds;
-    std::vector<std::pair<hwc2_display_t, int64_t>> pendingVsyncs;
-    std::vector<std::pair<hwc2_display_t, int>> pendingHotplugs;
-
-    if (descriptor == Callback::Refresh) {
-        hasPendingInvalidate = mHasPendingInvalidate;
-        if (hasPendingInvalidate) {
-            for (auto& displayPair : mDisplays) {
-                displayIds.emplace_back(displayPair.first);
-            }
-        }
-        mHasPendingInvalidate = false;
-    } else if (descriptor == Callback::Vsync) {
-        for (auto pending : mPendingVsyncs) {
-            auto hwc1DisplayId = pending.first;
-            if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
-                ALOGE("hwc1Vsync: Couldn't find display for HWC1 id %d",
-                        hwc1DisplayId);
-                continue;
-            }
-            auto displayId = mHwc1DisplayMap[hwc1DisplayId];
-            auto timestamp = pending.second;
-            pendingVsyncs.emplace_back(displayId, timestamp);
-        }
-        mPendingVsyncs.clear();
-    } else if (descriptor == Callback::Hotplug) {
-        // Hotplug the primary display
-        pendingHotplugs.emplace_back(mHwc1DisplayMap[HWC_DISPLAY_PRIMARY],
-                static_cast<int32_t>(Connection::Connected));
-
-        for (auto pending : mPendingHotplugs) {
-            auto hwc1DisplayId = pending.first;
-            if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
-                ALOGE("hwc1Hotplug: Couldn't find display for HWC1 id %d",
-                        hwc1DisplayId);
-                continue;
-            }
-            auto displayId = mHwc1DisplayMap[hwc1DisplayId];
-            auto connected = pending.second;
-            pendingHotplugs.emplace_back(displayId, connected);
-        }
-    }
-
-    // Call pending callbacks without the state lock held
-    lock.unlock();
-
-    if (hasPendingInvalidate) {
-        auto refresh = reinterpret_cast<HWC2_PFN_REFRESH>(pointer);
-        for (auto displayId : displayIds) {
-            refresh(callbackData, displayId);
-        }
-    }
-    if (!pendingVsyncs.empty()) {
-        auto vsync = reinterpret_cast<HWC2_PFN_VSYNC>(pointer);
-        for (auto& pendingVsync : pendingVsyncs) {
-            vsync(callbackData, pendingVsync.first, pendingVsync.second);
-        }
-    }
-    if (!pendingHotplugs.empty()) {
-        auto hotplug = reinterpret_cast<HWC2_PFN_HOTPLUG>(pointer);
-        for (auto& pendingHotplug : pendingHotplugs) {
-            hotplug(callbackData, pendingHotplug.first, pendingHotplug.second);
-        }
-    }
-    return Error::None;
-}
-
-// Display functions
-
-std::atomic<hwc2_display_t> HWC2On1Adapter::Display::sNextId(1);
-
-HWC2On1Adapter::Display::Display(HWC2On1Adapter& device, HWC2::DisplayType type)
-  : mId(sNextId++),
-    mDevice(device),
-    mStateMutex(),
-    mHwc1RequestedContents(nullptr),
-    mRetireFence(),
-    mChanges(),
-    mHwc1Id(-1),
-    mConfigs(),
-    mActiveConfig(nullptr),
-    mActiveColorMode(static_cast<android_color_mode_t>(-1)),
-    mName(),
-    mType(type),
-    mPowerMode(PowerMode::Off),
-    mVsyncEnabled(Vsync::Invalid),
-    mClientTarget(),
-    mOutputBuffer(),
-    mHasColorTransform(false),
-    mLayers(),
-    mHwc1LayerMap(),
-    mNumAvailableRects(0),
-    mNextAvailableRect(nullptr),
-    mGeometryChanged(false)
-    {}
-
-Error HWC2On1Adapter::Display::acceptChanges() {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    if (!mChanges) {
-        ALOGV("[%" PRIu64 "] acceptChanges failed, not validated", mId);
-        return Error::NotValidated;
-    }
-
-    ALOGV("[%" PRIu64 "] acceptChanges", mId);
-
-    for (auto& change : mChanges->getTypeChanges()) {
-        auto layerId = change.first;
-        auto type = change.second;
-        if (mDevice.mLayers.count(layerId) == 0) {
-            // This should never happen but somehow does.
-            ALOGW("Cannot accept change for unknown layer (%" PRIu64 ")",
-                  layerId);
-            continue;
-        }
-        auto layer = mDevice.mLayers[layerId];
-        layer->setCompositionType(type);
-    }
-
-    mChanges->clearTypeChanges();
-
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::createLayer(hwc2_layer_t* outLayerId) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    auto layer = *mLayers.emplace(std::make_shared<Layer>(*this));
-    mDevice.mLayers.emplace(std::make_pair(layer->getId(), layer));
-    *outLayerId = layer->getId();
-    ALOGV("[%" PRIu64 "] created layer %" PRIu64, mId, *outLayerId);
-    markGeometryChanged();
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::destroyLayer(hwc2_layer_t layerId) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    const auto mapLayer = mDevice.mLayers.find(layerId);
-    if (mapLayer == mDevice.mLayers.end()) {
-        ALOGV("[%" PRIu64 "] destroyLayer(%" PRIu64 ") failed: no such layer",
-                mId, layerId);
-        return Error::BadLayer;
-    }
-    const auto layer = mapLayer->second;
-    mDevice.mLayers.erase(mapLayer);
-    const auto zRange = mLayers.equal_range(layer);
-    for (auto current = zRange.first; current != zRange.second; ++current) {
-        if (**current == *layer) {
-            current = mLayers.erase(current);
-            break;
-        }
-    }
-    ALOGV("[%" PRIu64 "] destroyed layer %" PRIu64, mId, layerId);
-    markGeometryChanged();
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::getActiveConfig(hwc2_config_t* outConfig) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    if (!mActiveConfig) {
-        ALOGV("[%" PRIu64 "] getActiveConfig --> %s", mId,
-                to_string(Error::BadConfig).c_str());
-        return Error::BadConfig;
-    }
-    auto configId = mActiveConfig->getId();
-    ALOGV("[%" PRIu64 "] getActiveConfig --> %u", mId, configId);
-    *outConfig = configId;
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::getAttribute(hwc2_config_t configId,
-        Attribute attribute, int32_t* outValue) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    if (configId > mConfigs.size() || !mConfigs[configId]->isOnDisplay(*this)) {
-        ALOGV("[%" PRIu64 "] getAttribute failed: bad config (%u)", mId,
-                configId);
-        return Error::BadConfig;
-    }
-    *outValue = mConfigs[configId]->getAttribute(attribute);
-    ALOGV("[%" PRIu64 "] getAttribute(%u, %s) --> %d", mId, configId,
-            to_string(attribute).c_str(), *outValue);
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::getChangedCompositionTypes(
-        uint32_t* outNumElements, hwc2_layer_t* outLayers, int32_t* outTypes) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    if (!mChanges) {
-        ALOGE("[%" PRIu64 "] getChangedCompositionTypes failed: not validated",
-                mId);
-        return Error::NotValidated;
-    }
-
-    if ((outLayers == nullptr) || (outTypes == nullptr)) {
-        *outNumElements = mChanges->getTypeChanges().size();
-        return Error::None;
-    }
-
-    uint32_t numWritten = 0;
-    for (const auto& element : mChanges->getTypeChanges()) {
-        if (numWritten == *outNumElements) {
-            break;
-        }
-        auto layerId = element.first;
-        auto intType = static_cast<int32_t>(element.second);
-        ALOGV("Adding %" PRIu64 " %s", layerId,
-                to_string(element.second).c_str());
-        outLayers[numWritten] = layerId;
-        outTypes[numWritten] = intType;
-        ++numWritten;
-    }
-    *outNumElements = numWritten;
-
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::getColorModes(uint32_t* outNumModes,
-        int32_t* outModes) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    if (!outModes) {
-        *outNumModes = mColorModes.size();
-        return Error::None;
-    }
-    uint32_t numModes = std::min(*outNumModes,
-            static_cast<uint32_t>(mColorModes.size()));
-    std::copy_n(mColorModes.cbegin(), numModes, outModes);
-    *outNumModes = numModes;
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::getConfigs(uint32_t* outNumConfigs,
-        hwc2_config_t* outConfigs) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    if (!outConfigs) {
-        *outNumConfigs = mConfigs.size();
-        return Error::None;
-    }
-    uint32_t numWritten = 0;
-    for (const auto& config : mConfigs) {
-        if (numWritten == *outNumConfigs) {
-            break;
-        }
-        outConfigs[numWritten] = config->getId();
-        ++numWritten;
-    }
-    *outNumConfigs = numWritten;
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::getDozeSupport(int32_t* outSupport) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    if (mDevice.mHwc1MinorVersion < 4 || mHwc1Id != 0) {
-        *outSupport = 0;
-    } else {
-        *outSupport = 1;
-    }
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::getHdrCapabilities(uint32_t* outNumTypes,
-        int32_t* /*outTypes*/, float* /*outMaxLuminance*/,
-        float* /*outMaxAverageLuminance*/, float* /*outMinLuminance*/) {
-    // This isn't supported on HWC1, so per the HWC2 header, return numTypes = 0
-    *outNumTypes = 0;
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::getName(uint32_t* outSize, char* outName) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    if (!outName) {
-        *outSize = mName.size();
-        return Error::None;
-    }
-    auto numCopied = mName.copy(outName, *outSize);
-    *outSize = numCopied;
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::getReleaseFences(uint32_t* outNumElements,
-        hwc2_layer_t* outLayers, int32_t* outFences) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    uint32_t numWritten = 0;
-    bool outputsNonNull = (outLayers != nullptr) && (outFences != nullptr);
-    for (const auto& layer : mLayers) {
-        if (outputsNonNull && (numWritten == *outNumElements)) {
-            break;
-        }
-
-        auto releaseFence = layer->getReleaseFence();
-        if (releaseFence != MiniFence::NO_FENCE) {
-            if (outputsNonNull) {
-                outLayers[numWritten] = layer->getId();
-                outFences[numWritten] = releaseFence->dup();
-            }
-            ++numWritten;
-        }
-    }
-    *outNumElements = numWritten;
-
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::getRequests(int32_t* outDisplayRequests,
-        uint32_t* outNumElements, hwc2_layer_t* outLayers,
-        int32_t* outLayerRequests) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    if (!mChanges) {
-        return Error::NotValidated;
-    }
-
-    if (outLayers == nullptr || outLayerRequests == nullptr) {
-        *outNumElements = mChanges->getNumLayerRequests();
-        return Error::None;
-    }
-
-    // Display requests (HWC2::DisplayRequest) are not supported by hwc1:
-    // A hwc1 has always zero requests for the client.
-    *outDisplayRequests = 0;
-
-    uint32_t numWritten = 0;
-    for (const auto& request : mChanges->getLayerRequests()) {
-        if (numWritten == *outNumElements) {
-            break;
-        }
-        outLayers[numWritten] = request.first;
-        outLayerRequests[numWritten] = static_cast<int32_t>(request.second);
-        ++numWritten;
-    }
-
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::getType(int32_t* outType) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    *outType = static_cast<int32_t>(mType);
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::present(int32_t* outRetireFence) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    if (mChanges) {
-        Error error = mDevice.setAllDisplays();
-        if (error != Error::None) {
-            ALOGE("[%" PRIu64 "] present: setAllDisplaysFailed (%s)", mId,
-                    to_string(error).c_str());
-            return error;
-        }
-    }
-
-    *outRetireFence = mRetireFence.get()->dup();
-    ALOGV("[%" PRIu64 "] present returning retire fence %d", mId,
-            *outRetireFence);
-
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::setActiveConfig(hwc2_config_t configId) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    auto config = getConfig(configId);
-    if (!config) {
-        return Error::BadConfig;
-    }
-    if (config == mActiveConfig) {
-        return Error::None;
-    }
-
-    if (mDevice.mHwc1MinorVersion >= 4) {
-        uint32_t hwc1Id = 0;
-        auto error = config->getHwc1IdForColorMode(mActiveColorMode, &hwc1Id);
-        if (error != Error::None) {
-            return error;
-        }
-
-        int intError = mDevice.mHwc1Device->setActiveConfig(mDevice.mHwc1Device,
-                mHwc1Id, static_cast<int>(hwc1Id));
-        if (intError != 0) {
-            ALOGE("setActiveConfig: Failed to set active config on HWC1 (%d)",
-                intError);
-            return Error::BadConfig;
-        }
-        mActiveConfig = config;
-    }
-
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::setClientTarget(buffer_handle_t target,
-        int32_t acquireFence, int32_t /*dataspace*/, hwc_region_t /*damage*/) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    ALOGV("[%" PRIu64 "] setClientTarget(%p, %d)", mId, target, acquireFence);
-    mClientTarget.setBuffer(target);
-    mClientTarget.setFence(acquireFence);
-    // dataspace and damage can't be used by HWC1, so ignore them
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::setColorMode(android_color_mode_t mode) {
-    std::unique_lock<std::recursive_mutex> lock (mStateMutex);
-
-    ALOGV("[%" PRIu64 "] setColorMode(%d)", mId, mode);
-
-    if (mode == mActiveColorMode) {
-        return Error::None;
-    }
-    if (mColorModes.count(mode) == 0) {
-        ALOGE("[%" PRIu64 "] Mode %d not found in mColorModes", mId, mode);
-        return Error::Unsupported;
-    }
-
-    uint32_t hwc1Config = 0;
-    auto error = mActiveConfig->getHwc1IdForColorMode(mode, &hwc1Config);
-    if (error != Error::None) {
-        return error;
-    }
-
-    ALOGV("[%" PRIu64 "] Setting HWC1 config %u", mId, hwc1Config);
-    int intError = mDevice.mHwc1Device->setActiveConfig(mDevice.mHwc1Device,
-            mHwc1Id, hwc1Config);
-    if (intError != 0) {
-        ALOGE("[%" PRIu64 "] Failed to set HWC1 config (%d)", mId, intError);
-        return Error::Unsupported;
-    }
-
-    mActiveColorMode = mode;
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::setColorTransform(android_color_transform_t hint) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    ALOGV("%" PRIu64 "] setColorTransform(%d)", mId,
-            static_cast<int32_t>(hint));
-    mHasColorTransform = (hint != HAL_COLOR_TRANSFORM_IDENTITY);
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::setOutputBuffer(buffer_handle_t buffer,
-        int32_t releaseFence) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    ALOGV("[%" PRIu64 "] setOutputBuffer(%p, %d)", mId, buffer, releaseFence);
-    mOutputBuffer.setBuffer(buffer);
-    mOutputBuffer.setFence(releaseFence);
-    return Error::None;
-}
-
-static bool isValid(PowerMode mode) {
-    switch (mode) {
-        case PowerMode::Off: // Fall-through
-        case PowerMode::DozeSuspend: // Fall-through
-        case PowerMode::Doze: // Fall-through
-        case PowerMode::On: return true;
-    }
-}
-
-static int getHwc1PowerMode(PowerMode mode) {
-    switch (mode) {
-        case PowerMode::Off: return HWC_POWER_MODE_OFF;
-        case PowerMode::DozeSuspend: return HWC_POWER_MODE_DOZE_SUSPEND;
-        case PowerMode::Doze: return HWC_POWER_MODE_DOZE;
-        case PowerMode::On: return HWC_POWER_MODE_NORMAL;
-    }
-}
-
-Error HWC2On1Adapter::Display::setPowerMode(PowerMode mode) {
-    if (!isValid(mode)) {
-        return Error::BadParameter;
-    }
-    if (mode == mPowerMode) {
-        return Error::None;
-    }
-
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    int error = 0;
-    if (mDevice.mHwc1MinorVersion < 4) {
-        error = mDevice.mHwc1Device->blank(mDevice.mHwc1Device, mHwc1Id,
-                mode == PowerMode::Off);
-    } else {
-        error = mDevice.mHwc1Device->setPowerMode(mDevice.mHwc1Device,
-                mHwc1Id, getHwc1PowerMode(mode));
-    }
-    ALOGE_IF(error != 0, "setPowerMode: Failed to set power mode on HWC1 (%d)",
-            error);
-
-    ALOGV("[%" PRIu64 "] setPowerMode(%s)", mId, to_string(mode).c_str());
-    mPowerMode = mode;
-    return Error::None;
-}
-
-static bool isValid(Vsync enable) {
-    switch (enable) {
-        case Vsync::Enable: // Fall-through
-        case Vsync::Disable: return true;
-        case Vsync::Invalid: return false;
-    }
-}
-
-Error HWC2On1Adapter::Display::setVsyncEnabled(Vsync enable) {
-    if (!isValid(enable)) {
-        return Error::BadParameter;
-    }
-    if (enable == mVsyncEnabled) {
-        return Error::None;
-    }
-
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    int error = mDevice.mHwc1Device->eventControl(mDevice.mHwc1Device,
-            mHwc1Id, HWC_EVENT_VSYNC, enable == Vsync::Enable);
-    ALOGE_IF(error != 0, "setVsyncEnabled: Failed to set vsync on HWC1 (%d)",
-            error);
-
-    mVsyncEnabled = enable;
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::validate(uint32_t* outNumTypes,
-        uint32_t* outNumRequests) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    if (!mChanges) {
-        if (!mDevice.prepareAllDisplays()) {
-            return Error::BadDisplay;
-        }
-    } else {
-        ALOGE("Validate was called more than once!");
-    }
-
-    *outNumTypes = mChanges->getNumTypes();
-    *outNumRequests = mChanges->getNumLayerRequests();
-    ALOGV("[%" PRIu64 "] validate --> %u types, %u requests", mId, *outNumTypes,
-            *outNumRequests);
-    for (auto request : mChanges->getTypeChanges()) {
-        ALOGV("Layer %" PRIu64 " --> %s", request.first,
-                to_string(request.second).c_str());
-    }
-    return *outNumTypes > 0 ? Error::HasChanges : Error::None;
-}
-
-Error HWC2On1Adapter::Display::updateLayerZ(hwc2_layer_t layerId, uint32_t z) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    const auto mapLayer = mDevice.mLayers.find(layerId);
-    if (mapLayer == mDevice.mLayers.end()) {
-        ALOGE("[%" PRIu64 "] updateLayerZ failed to find layer", mId);
-        return Error::BadLayer;
-    }
-
-    const auto layer = mapLayer->second;
-    const auto zRange = mLayers.equal_range(layer);
-    bool layerOnDisplay = false;
-    for (auto current = zRange.first; current != zRange.second; ++current) {
-        if (**current == *layer) {
-            if ((*current)->getZ() == z) {
-                // Don't change anything if the Z hasn't changed
-                return Error::None;
-            }
-            current = mLayers.erase(current);
-            layerOnDisplay = true;
-            break;
-        }
-    }
-
-    if (!layerOnDisplay) {
-        ALOGE("[%" PRIu64 "] updateLayerZ failed to find layer on display",
-                mId);
-        return Error::BadLayer;
-    }
-
-    layer->setZ(z);
-    mLayers.emplace(std::move(layer));
-    markGeometryChanged();
-
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Display::getClientTargetSupport(uint32_t width, uint32_t height,
-                                      int32_t format, int32_t dataspace){
-    if (mActiveConfig == nullptr) {
-        return Error::Unsupported;
-    }
-
-    if (width == mActiveConfig->getAttribute(Attribute::Width) &&
-            height == mActiveConfig->getAttribute(Attribute::Height) &&
-            format == HAL_PIXEL_FORMAT_RGBA_8888 &&
-            dataspace == HAL_DATASPACE_UNKNOWN) {
-        return Error::None;
-    }
-
-    return Error::Unsupported;
-}
-
-static constexpr uint32_t ATTRIBUTES_WITH_COLOR[] = {
-    HWC_DISPLAY_VSYNC_PERIOD,
-    HWC_DISPLAY_WIDTH,
-    HWC_DISPLAY_HEIGHT,
-    HWC_DISPLAY_DPI_X,
-    HWC_DISPLAY_DPI_Y,
-    HWC_DISPLAY_COLOR_TRANSFORM,
-    HWC_DISPLAY_NO_ATTRIBUTE,
-};
-
-static constexpr uint32_t ATTRIBUTES_WITHOUT_COLOR[] = {
-    HWC_DISPLAY_VSYNC_PERIOD,
-    HWC_DISPLAY_WIDTH,
-    HWC_DISPLAY_HEIGHT,
-    HWC_DISPLAY_DPI_X,
-    HWC_DISPLAY_DPI_Y,
-    HWC_DISPLAY_NO_ATTRIBUTE,
-};
-
-static constexpr size_t NUM_ATTRIBUTES_WITH_COLOR =
-        sizeof(ATTRIBUTES_WITH_COLOR) / sizeof(uint32_t);
-static_assert(sizeof(ATTRIBUTES_WITH_COLOR) > sizeof(ATTRIBUTES_WITHOUT_COLOR),
-        "Attribute tables have unexpected sizes");
-
-static constexpr uint32_t ATTRIBUTE_MAP_WITH_COLOR[] = {
-    6, // HWC_DISPLAY_NO_ATTRIBUTE = 0
-    0, // HWC_DISPLAY_VSYNC_PERIOD = 1,
-    1, // HWC_DISPLAY_WIDTH = 2,
-    2, // HWC_DISPLAY_HEIGHT = 3,
-    3, // HWC_DISPLAY_DPI_X = 4,
-    4, // HWC_DISPLAY_DPI_Y = 5,
-    5, // HWC_DISPLAY_COLOR_TRANSFORM = 6,
-};
-
-static constexpr uint32_t ATTRIBUTE_MAP_WITHOUT_COLOR[] = {
-    5, // HWC_DISPLAY_NO_ATTRIBUTE = 0
-    0, // HWC_DISPLAY_VSYNC_PERIOD = 1,
-    1, // HWC_DISPLAY_WIDTH = 2,
-    2, // HWC_DISPLAY_HEIGHT = 3,
-    3, // HWC_DISPLAY_DPI_X = 4,
-    4, // HWC_DISPLAY_DPI_Y = 5,
-};
-
-template <uint32_t attribute>
-static constexpr bool attributesMatch()
-{
-    bool match = (attribute ==
-            ATTRIBUTES_WITH_COLOR[ATTRIBUTE_MAP_WITH_COLOR[attribute]]);
-    if (attribute == HWC_DISPLAY_COLOR_TRANSFORM) {
-        return match;
-    }
-
-    return match && (attribute ==
-            ATTRIBUTES_WITHOUT_COLOR[ATTRIBUTE_MAP_WITHOUT_COLOR[attribute]]);
-}
-static_assert(attributesMatch<HWC_DISPLAY_VSYNC_PERIOD>(),
-        "Tables out of sync");
-static_assert(attributesMatch<HWC_DISPLAY_WIDTH>(), "Tables out of sync");
-static_assert(attributesMatch<HWC_DISPLAY_HEIGHT>(), "Tables out of sync");
-static_assert(attributesMatch<HWC_DISPLAY_DPI_X>(), "Tables out of sync");
-static_assert(attributesMatch<HWC_DISPLAY_DPI_Y>(), "Tables out of sync");
-static_assert(attributesMatch<HWC_DISPLAY_COLOR_TRANSFORM>(),
-        "Tables out of sync");
-
-void HWC2On1Adapter::Display::populateConfigs() {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    ALOGV("[%" PRIu64 "] populateConfigs", mId);
-
-    if (mHwc1Id == -1) {
-        ALOGE("populateConfigs: HWC1 ID not set");
-        return;
-    }
-
-    const size_t MAX_NUM_CONFIGS = 128;
-    uint32_t configs[MAX_NUM_CONFIGS] = {};
-    size_t numConfigs = MAX_NUM_CONFIGS;
-    mDevice.mHwc1Device->getDisplayConfigs(mDevice.mHwc1Device, mHwc1Id,
-            configs, &numConfigs);
-
-    for (size_t c = 0; c < numConfigs; ++c) {
-        uint32_t hwc1ConfigId = configs[c];
-        auto newConfig = std::make_shared<Config>(*this);
-
-        int32_t values[NUM_ATTRIBUTES_WITH_COLOR] = {};
-        bool hasColor = true;
-        auto result = mDevice.mHwc1Device->getDisplayAttributes(
-                mDevice.mHwc1Device, mHwc1Id, hwc1ConfigId,
-                ATTRIBUTES_WITH_COLOR, values);
-        if (result != 0) {
-            mDevice.mHwc1Device->getDisplayAttributes(mDevice.mHwc1Device,
-                    mHwc1Id, hwc1ConfigId, ATTRIBUTES_WITHOUT_COLOR, values);
-            hasColor = false;
-        }
-
-        auto attributeMap = hasColor ?
-                ATTRIBUTE_MAP_WITH_COLOR : ATTRIBUTE_MAP_WITHOUT_COLOR;
-
-        newConfig->setAttribute(Attribute::VsyncPeriod,
-                values[attributeMap[HWC_DISPLAY_VSYNC_PERIOD]]);
-        newConfig->setAttribute(Attribute::Width,
-                values[attributeMap[HWC_DISPLAY_WIDTH]]);
-        newConfig->setAttribute(Attribute::Height,
-                values[attributeMap[HWC_DISPLAY_HEIGHT]]);
-        newConfig->setAttribute(Attribute::DpiX,
-                values[attributeMap[HWC_DISPLAY_DPI_X]]);
-        newConfig->setAttribute(Attribute::DpiY,
-                values[attributeMap[HWC_DISPLAY_DPI_Y]]);
-        if (hasColor) {
-            // In HWC1, color modes are referred to as color transforms. To avoid confusion with
-            // the HWC2 concept of color transforms, we internally refer to them as color modes for
-            // both HWC1 and 2.
-            newConfig->setAttribute(ColorMode,
-                    values[attributeMap[HWC_DISPLAY_COLOR_TRANSFORM]]);
-        }
-
-        // We can only do this after attempting to read the color mode
-        newConfig->setHwc1Id(hwc1ConfigId);
-
-        for (auto& existingConfig : mConfigs) {
-            if (existingConfig->merge(*newConfig)) {
-                ALOGV("Merged config %d with existing config %u: %s",
-                        hwc1ConfigId, existingConfig->getId(),
-                        existingConfig->toString().c_str());
-                newConfig.reset();
-                break;
-            }
-        }
-
-        // If it wasn't merged with any existing config, add it to the end
-        if (newConfig) {
-            newConfig->setId(static_cast<hwc2_config_t>(mConfigs.size()));
-            ALOGV("Found new config %u: %s", newConfig->getId(),
-                    newConfig->toString().c_str());
-            mConfigs.emplace_back(std::move(newConfig));
-        }
-    }
-
-    initializeActiveConfig();
-    populateColorModes();
-}
-
-void HWC2On1Adapter::Display::populateConfigs(uint32_t width, uint32_t height) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    mConfigs.emplace_back(std::make_shared<Config>(*this));
-    auto& config = mConfigs[0];
-
-    config->setAttribute(Attribute::Width, static_cast<int32_t>(width));
-    config->setAttribute(Attribute::Height, static_cast<int32_t>(height));
-    config->setHwc1Id(0);
-    config->setId(0);
-    mActiveConfig = config;
-}
-
-bool HWC2On1Adapter::Display::prepare() {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    // Only prepare display contents for displays HWC1 knows about
-    if (mHwc1Id == -1) {
-        return true;
-    }
-
-    // It doesn't make sense to prepare a display for which there is no active
-    // config, so return early
-    if (!mActiveConfig) {
-        ALOGE("[%" PRIu64 "] Attempted to prepare, but no config active", mId);
-        return false;
-    }
-
-    allocateRequestedContents();
-    assignHwc1LayerIds();
-
-    mHwc1RequestedContents->retireFenceFd = -1;
-    mHwc1RequestedContents->flags = 0;
-    if (mGeometryChanged) {
-        mHwc1RequestedContents->flags |= HWC_GEOMETRY_CHANGED;
-    }
-    mHwc1RequestedContents->outbuf = mOutputBuffer.getBuffer();
-    mHwc1RequestedContents->outbufAcquireFenceFd = mOutputBuffer.getFence();
-
-    // +1 is for framebuffer target layer.
-    mHwc1RequestedContents->numHwLayers = mLayers.size() + 1;
-    for (auto& layer : mLayers) {
-        auto& hwc1Layer = mHwc1RequestedContents->hwLayers[layer->getHwc1Id()];
-        hwc1Layer.releaseFenceFd = -1;
-        hwc1Layer.acquireFenceFd = -1;
-        ALOGV("Applying states for layer %" PRIu64 " ", layer->getId());
-        layer->applyState(hwc1Layer);
-    }
-
-    prepareFramebufferTarget();
-
-    resetGeometryMarker();
-
-    return true;
-}
-
-void HWC2On1Adapter::Display::generateChanges() {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    mChanges.reset(new Changes);
-
-    size_t numLayers = mHwc1RequestedContents->numHwLayers;
-    for (size_t hwc1Id = 0; hwc1Id < numLayers; ++hwc1Id) {
-        const auto& receivedLayer = mHwc1RequestedContents->hwLayers[hwc1Id];
-        if (mHwc1LayerMap.count(hwc1Id) == 0) {
-            ALOGE_IF(receivedLayer.compositionType != HWC_FRAMEBUFFER_TARGET,
-                    "generateChanges: HWC1 layer %zd doesn't have a"
-                    " matching HWC2 layer, and isn't the framebuffer target",
-                    hwc1Id);
-            continue;
-        }
-
-        Layer& layer = *mHwc1LayerMap[hwc1Id];
-        updateTypeChanges(receivedLayer, layer);
-        updateLayerRequests(receivedLayer, layer);
-    }
-}
-
-bool HWC2On1Adapter::Display::hasChanges() const {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-    return mChanges != nullptr;
-}
-
-Error HWC2On1Adapter::Display::set(hwc_display_contents_1& hwcContents) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    if (!mChanges || (mChanges->getNumTypes() > 0)) {
-        ALOGE("[%" PRIu64 "] set failed: not validated", mId);
-        return Error::NotValidated;
-    }
-
-    // Set up the client/framebuffer target
-    auto numLayers = hwcContents.numHwLayers;
-
-    // Close acquire fences on FRAMEBUFFER layers, since they will not be used
-    // by HWC
-    for (size_t l = 0; l < numLayers - 1; ++l) {
-        auto& layer = hwcContents.hwLayers[l];
-        if (layer.compositionType == HWC_FRAMEBUFFER) {
-            ALOGV("Closing fence %d for layer %zd", layer.acquireFenceFd, l);
-            close(layer.acquireFenceFd);
-            layer.acquireFenceFd = -1;
-        }
-    }
-
-    auto& clientTargetLayer = hwcContents.hwLayers[numLayers - 1];
-    if (clientTargetLayer.compositionType == HWC_FRAMEBUFFER_TARGET) {
-        clientTargetLayer.handle = mClientTarget.getBuffer();
-        clientTargetLayer.acquireFenceFd = mClientTarget.getFence();
-    } else {
-        ALOGE("[%" PRIu64 "] set: last HWC layer wasn't FRAMEBUFFER_TARGET",
-                mId);
-    }
-
-    mChanges.reset();
-
-    return Error::None;
-}
-
-void HWC2On1Adapter::Display::addRetireFence(int fenceFd) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-    mRetireFence.add(fenceFd);
-}
-
-void HWC2On1Adapter::Display::addReleaseFences(
-        const hwc_display_contents_1_t& hwcContents) {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    size_t numLayers = hwcContents.numHwLayers;
-    for (size_t hwc1Id = 0; hwc1Id < numLayers; ++hwc1Id) {
-        const auto& receivedLayer = hwcContents.hwLayers[hwc1Id];
-        if (mHwc1LayerMap.count(hwc1Id) == 0) {
-            if (receivedLayer.compositionType != HWC_FRAMEBUFFER_TARGET) {
-                ALOGE("addReleaseFences: HWC1 layer %zd doesn't have a"
-                        " matching HWC2 layer, and isn't the framebuffer"
-                        " target", hwc1Id);
-            }
-            // Close the framebuffer target release fence since we will use the
-            // display retire fence instead
-            if (receivedLayer.releaseFenceFd != -1) {
-                close(receivedLayer.releaseFenceFd);
-            }
-            continue;
-        }
-
-        Layer& layer = *mHwc1LayerMap[hwc1Id];
-        ALOGV("Adding release fence %d to layer %" PRIu64,
-                receivedLayer.releaseFenceFd, layer.getId());
-        layer.addReleaseFence(receivedLayer.releaseFenceFd);
-    }
-}
-
-bool HWC2On1Adapter::Display::hasColorTransform() const {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-    return mHasColorTransform;
-}
-
-static std::string hwc1CompositionString(int32_t type) {
-    switch (type) {
-        case HWC_FRAMEBUFFER: return "Framebuffer";
-        case HWC_OVERLAY: return "Overlay";
-        case HWC_BACKGROUND: return "Background";
-        case HWC_FRAMEBUFFER_TARGET: return "FramebufferTarget";
-        case HWC_SIDEBAND: return "Sideband";
-        case HWC_CURSOR_OVERLAY: return "CursorOverlay";
-        default:
-            return std::string("Unknown (") + std::to_string(type) + ")";
-    }
-}
-
-static std::string hwc1TransformString(int32_t transform) {
-    switch (transform) {
-        case 0: return "None";
-        case HWC_TRANSFORM_FLIP_H: return "FlipH";
-        case HWC_TRANSFORM_FLIP_V: return "FlipV";
-        case HWC_TRANSFORM_ROT_90: return "Rotate90";
-        case HWC_TRANSFORM_ROT_180: return "Rotate180";
-        case HWC_TRANSFORM_ROT_270: return "Rotate270";
-        case HWC_TRANSFORM_FLIP_H_ROT_90: return "FlipHRotate90";
-        case HWC_TRANSFORM_FLIP_V_ROT_90: return "FlipVRotate90";
-        default:
-            return std::string("Unknown (") + std::to_string(transform) + ")";
-    }
-}
-
-static std::string hwc1BlendModeString(int32_t mode) {
-    switch (mode) {
-        case HWC_BLENDING_NONE: return "None";
-        case HWC_BLENDING_PREMULT: return "Premultiplied";
-        case HWC_BLENDING_COVERAGE: return "Coverage";
-        default:
-            return std::string("Unknown (") + std::to_string(mode) + ")";
-    }
-}
-
-static std::string rectString(hwc_rect_t rect) {
-    std::stringstream output;
-    output << "[" << rect.left << ", " << rect.top << ", ";
-    output << rect.right << ", " << rect.bottom << "]";
-    return output.str();
-}
-
-static std::string approximateFloatString(float f) {
-    if (static_cast<int32_t>(f) == f) {
-        return std::to_string(static_cast<int32_t>(f));
-    }
-    int32_t truncated = static_cast<int32_t>(f * 10);
-    bool approximate = (static_cast<float>(truncated) != f * 10);
-    const size_t BUFFER_SIZE = 32;
-    char buffer[BUFFER_SIZE] = {};
-    auto bytesWritten = snprintf(buffer, BUFFER_SIZE,
-            "%s%.1f", approximate ? "~" : "", f);
-    return std::string(buffer, bytesWritten);
-}
-
-static std::string frectString(hwc_frect_t frect) {
-    std::stringstream output;
-    output << "[" << approximateFloatString(frect.left) << ", ";
-    output << approximateFloatString(frect.top) << ", ";
-    output << approximateFloatString(frect.right) << ", ";
-    output << approximateFloatString(frect.bottom) << "]";
-    return output.str();
-}
-
-static std::string colorString(hwc_color_t color) {
-    std::stringstream output;
-    output << "RGBA [";
-    output << static_cast<int32_t>(color.r) << ", ";
-    output << static_cast<int32_t>(color.g) << ", ";
-    output << static_cast<int32_t>(color.b) << ", ";
-    output << static_cast<int32_t>(color.a) << "]";
-    return output.str();
-}
-
-static std::string alphaString(float f) {
-    const size_t BUFFER_SIZE = 8;
-    char buffer[BUFFER_SIZE] = {};
-    auto bytesWritten = snprintf(buffer, BUFFER_SIZE, "%.3f", f);
-    return std::string(buffer, bytesWritten);
-}
-
-static std::string to_string(const hwc_layer_1_t& hwcLayer,
-        int32_t hwc1MinorVersion) {
-    const char* fill = "          ";
-
-    std::stringstream output;
-
-    output << "  Composition: " <<
-            hwc1CompositionString(hwcLayer.compositionType);
-
-    if (hwcLayer.compositionType == HWC_BACKGROUND) {
-        output << "  Color: " << colorString(hwcLayer.backgroundColor) << '\n';
-    } else if (hwcLayer.compositionType == HWC_SIDEBAND) {
-        output << "  Stream: " << hwcLayer.sidebandStream << '\n';
-    } else {
-        output << "  Buffer: " << hwcLayer.handle << "/" <<
-                hwcLayer.acquireFenceFd << '\n';
-    }
-
-    output << fill << "Display frame: " << rectString(hwcLayer.displayFrame) <<
-            '\n';
-
-    output << fill << "Source crop: ";
-    if (hwc1MinorVersion >= 3) {
-        output << frectString(hwcLayer.sourceCropf) << '\n';
-    } else {
-        output << rectString(hwcLayer.sourceCropi) << '\n';
-    }
-
-    output << fill << "Transform: " << hwc1TransformString(hwcLayer.transform);
-    output << "  Blend mode: " << hwc1BlendModeString(hwcLayer.blending);
-    if (hwcLayer.planeAlpha != 0xFF) {
-        output << "  Alpha: " << alphaString(hwcLayer.planeAlpha / 255.0f);
-    }
-    output << '\n';
-
-    if (hwcLayer.hints != 0) {
-        output << fill << "Hints:";
-        if ((hwcLayer.hints & HWC_HINT_TRIPLE_BUFFER) != 0) {
-            output << " TripleBuffer";
-        }
-        if ((hwcLayer.hints & HWC_HINT_CLEAR_FB) != 0) {
-            output << " ClearFB";
-        }
-        output << '\n';
-    }
-
-    if (hwcLayer.flags != 0) {
-        output << fill << "Flags:";
-        if ((hwcLayer.flags & HWC_SKIP_LAYER) != 0) {
-            output << " SkipLayer";
-        }
-        if ((hwcLayer.flags & HWC_IS_CURSOR_LAYER) != 0) {
-            output << " IsCursorLayer";
-        }
-        output << '\n';
-    }
-
-    return output.str();
-}
-
-static std::string to_string(const hwc_display_contents_1_t& hwcContents,
-        int32_t hwc1MinorVersion) {
-    const char* fill = "      ";
-
-    std::stringstream output;
-    output << fill << "Geometry changed: " <<
-            ((hwcContents.flags & HWC_GEOMETRY_CHANGED) != 0 ? "Y\n" : "N\n");
-
-    output << fill << hwcContents.numHwLayers << " Layer" <<
-            ((hwcContents.numHwLayers == 1) ? "\n" : "s\n");
-    for (size_t layer = 0; layer < hwcContents.numHwLayers; ++layer) {
-        output << fill << "  Layer " << layer;
-        output << to_string(hwcContents.hwLayers[layer], hwc1MinorVersion);
-    }
-
-    if (hwcContents.outbuf != nullptr) {
-        output << fill << "Output buffer: " << hwcContents.outbuf << "/" <<
-                hwcContents.outbufAcquireFenceFd << '\n';
-    }
-
-    return output.str();
-}
-
-std::string HWC2On1Adapter::Display::dump() const {
-    std::unique_lock<std::recursive_mutex> lock(mStateMutex);
-
-    std::stringstream output;
-
-    output << "  Display " << mId << ": ";
-    output << to_string(mType) << "  ";
-    output << "HWC1 ID: " << mHwc1Id << "  ";
-    output << "Power mode: " << to_string(mPowerMode) << "  ";
-    output << "Vsync: " << to_string(mVsyncEnabled) << '\n';
-
-    output << "    Color modes [active]:";
-    for (const auto& mode : mColorModes) {
-        if (mode == mActiveColorMode) {
-            output << " [" << mode << ']';
-        } else {
-            output << " " << mode;
-        }
-    }
-    output << '\n';
-
-    output << "    " << mConfigs.size() << " Config" <<
-            (mConfigs.size() == 1 ? "" : "s") << " (* active)\n";
-    for (const auto& config : mConfigs) {
-        output << (config == mActiveConfig ? "    * " : "      ");
-        output << config->toString(true) << '\n';
-    }
-
-    output << "    " << mLayers.size() << " Layer" <<
-            (mLayers.size() == 1 ? "" : "s") << '\n';
-    for (const auto& layer : mLayers) {
-        output << layer->dump();
-    }
-
-    output << "    Client target: " << mClientTarget.getBuffer() << '\n';
-
-    if (mOutputBuffer.getBuffer() != nullptr) {
-        output << "    Output buffer: " << mOutputBuffer.getBuffer() << '\n';
-    }
-
-    if (mHwc1RequestedContents) {
-        output << "    Last requested HWC1 state\n";
-        output << to_string(*mHwc1RequestedContents, mDevice.mHwc1MinorVersion);
-    }
-
-    return output.str();
-}
-
-hwc_rect_t* HWC2On1Adapter::Display::GetRects(size_t numRects) {
-    if (numRects == 0) {
-        return nullptr;
-    }
-
-    if (numRects > mNumAvailableRects) {
-        // This should NEVER happen since we calculated how many rects the
-        // display would need.
-        ALOGE("Rect allocation failure! SF is likely to crash soon!");
-        return nullptr;
-
-    }
-    hwc_rect_t* rects = mNextAvailableRect;
-    mNextAvailableRect += numRects;
-    mNumAvailableRects -= numRects;
-    return rects;
-}
-
-hwc_display_contents_1* HWC2On1Adapter::Display::getDisplayContents() {
-    return mHwc1RequestedContents.get();
-}
-
-void HWC2On1Adapter::Display::Config::setAttribute(HWC2::Attribute attribute,
-        int32_t value) {
-    mAttributes[attribute] = value;
-}
-
-int32_t HWC2On1Adapter::Display::Config::getAttribute(Attribute attribute) const {
-    if (mAttributes.count(attribute) == 0) {
-        return -1;
-    }
-    return mAttributes.at(attribute);
-}
-
-void HWC2On1Adapter::Display::Config::setHwc1Id(uint32_t id) {
-    android_color_mode_t colorMode = static_cast<android_color_mode_t>(getAttribute(ColorMode));
-    mHwc1Ids.emplace(colorMode, id);
-}
-
-bool HWC2On1Adapter::Display::Config::hasHwc1Id(uint32_t id) const {
-    for (const auto& idPair : mHwc1Ids) {
-        if (id == idPair.second) {
-            return true;
-        }
-    }
-    return false;
-}
-
-Error HWC2On1Adapter::Display::Config::getColorModeForHwc1Id(
-        uint32_t id, android_color_mode_t* outMode) const {
-    for (const auto& idPair : mHwc1Ids) {
-        if (id == idPair.second) {
-            *outMode = idPair.first;
-            return Error::None;
-        }
-    }
-    ALOGE("Unable to find color mode for HWC ID %" PRIu32 " on config %u", id, mId);
-    return Error::BadParameter;
-}
-
-Error HWC2On1Adapter::Display::Config::getHwc1IdForColorMode(android_color_mode_t mode,
-        uint32_t* outId) const {
-    for (const auto& idPair : mHwc1Ids) {
-        if (mode == idPair.first) {
-            *outId = idPair.second;
-            return Error::None;
-        }
-    }
-    ALOGE("Unable to find HWC1 ID for color mode %d on config %u", mode, mId);
-    return Error::BadParameter;
-}
-
-bool HWC2On1Adapter::Display::Config::merge(const Config& other) {
-    auto attributes = {HWC2::Attribute::Width, HWC2::Attribute::Height,
-            HWC2::Attribute::VsyncPeriod, HWC2::Attribute::DpiX,
-            HWC2::Attribute::DpiY};
-    for (auto attribute : attributes) {
-        if (getAttribute(attribute) != other.getAttribute(attribute)) {
-            return false;
-        }
-    }
-    android_color_mode_t otherColorMode =
-            static_cast<android_color_mode_t>(other.getAttribute(ColorMode));
-    if (mHwc1Ids.count(otherColorMode) != 0) {
-        ALOGE("Attempted to merge two configs (%u and %u) which appear to be "
-                "identical", mHwc1Ids.at(otherColorMode),
-                other.mHwc1Ids.at(otherColorMode));
-        return false;
-    }
-    mHwc1Ids.emplace(otherColorMode,
-            other.mHwc1Ids.at(otherColorMode));
-    return true;
-}
-
-std::set<android_color_mode_t> HWC2On1Adapter::Display::Config::getColorModes() const {
-    std::set<android_color_mode_t> colorModes;
-    for (const auto& idPair : mHwc1Ids) {
-        colorModes.emplace(idPair.first);
-    }
-    return colorModes;
-}
-
-std::string HWC2On1Adapter::Display::Config::toString(bool splitLine) const {
-    std::string output;
-
-    const size_t BUFFER_SIZE = 100;
-    char buffer[BUFFER_SIZE] = {};
-    auto writtenBytes = snprintf(buffer, BUFFER_SIZE,
-            "%u x %u", mAttributes.at(HWC2::Attribute::Width),
-            mAttributes.at(HWC2::Attribute::Height));
-    output.append(buffer, writtenBytes);
-
-    if (mAttributes.count(HWC2::Attribute::VsyncPeriod) != 0) {
-        std::memset(buffer, 0, BUFFER_SIZE);
-        writtenBytes = snprintf(buffer, BUFFER_SIZE, " @ %.1f Hz",
-                1e9 / mAttributes.at(HWC2::Attribute::VsyncPeriod));
-        output.append(buffer, writtenBytes);
-    }
-
-    if (mAttributes.count(HWC2::Attribute::DpiX) != 0 &&
-            mAttributes.at(HWC2::Attribute::DpiX) != -1) {
-        std::memset(buffer, 0, BUFFER_SIZE);
-        writtenBytes = snprintf(buffer, BUFFER_SIZE,
-                ", DPI: %.1f x %.1f",
-                mAttributes.at(HWC2::Attribute::DpiX) / 1000.0f,
-                mAttributes.at(HWC2::Attribute::DpiY) / 1000.0f);
-        output.append(buffer, writtenBytes);
-    }
-
-    std::memset(buffer, 0, BUFFER_SIZE);
-    if (splitLine) {
-        writtenBytes = snprintf(buffer, BUFFER_SIZE,
-                "\n        HWC1 ID/Color transform:");
-    } else {
-        writtenBytes = snprintf(buffer, BUFFER_SIZE,
-                ", HWC1 ID/Color transform:");
-    }
-    output.append(buffer, writtenBytes);
-
-
-    for (const auto& id : mHwc1Ids) {
-        android_color_mode_t colorMode = id.first;
-        uint32_t hwc1Id = id.second;
-        std::memset(buffer, 0, BUFFER_SIZE);
-        if (colorMode == mDisplay.mActiveColorMode) {
-            writtenBytes = snprintf(buffer, BUFFER_SIZE, " [%u/%d]", hwc1Id,
-                    colorMode);
-        } else {
-            writtenBytes = snprintf(buffer, BUFFER_SIZE, " %u/%d", hwc1Id,
-                    colorMode);
-        }
-        output.append(buffer, writtenBytes);
-    }
-
-    return output;
-}
-
-std::shared_ptr<const HWC2On1Adapter::Display::Config>
-        HWC2On1Adapter::Display::getConfig(hwc2_config_t configId) const {
-    if (configId > mConfigs.size() || !mConfigs[configId]->isOnDisplay(*this)) {
-        return nullptr;
-    }
-    return mConfigs[configId];
-}
-
-void HWC2On1Adapter::Display::populateColorModes() {
-    mColorModes = mConfigs[0]->getColorModes();
-    for (const auto& config : mConfigs) {
-        std::set<android_color_mode_t> intersection;
-        auto configModes = config->getColorModes();
-        std::set_intersection(mColorModes.cbegin(), mColorModes.cend(),
-                configModes.cbegin(), configModes.cend(),
-                std::inserter(intersection, intersection.begin()));
-        std::swap(intersection, mColorModes);
-    }
-}
-
-void HWC2On1Adapter::Display::initializeActiveConfig() {
-    if (mDevice.mHwc1Device->getActiveConfig == nullptr) {
-        ALOGV("getActiveConfig is null, choosing config 0");
-        mActiveConfig = mConfigs[0];
-        mActiveColorMode = HAL_COLOR_MODE_NATIVE;
-        return;
-    }
-
-    auto activeConfig = mDevice.mHwc1Device->getActiveConfig(
-            mDevice.mHwc1Device, mHwc1Id);
-
-    // Some devices startup without an activeConfig:
-    // We need to set one ourselves.
-    if (activeConfig == HWC_ERROR) {
-        ALOGV("There is no active configuration: Picking the first one: 0.");
-        const int defaultIndex = 0;
-        mDevice.mHwc1Device->setActiveConfig(mDevice.mHwc1Device, mHwc1Id, defaultIndex);
-        activeConfig = defaultIndex;
-    }
-
-    for (const auto& config : mConfigs) {
-        if (config->hasHwc1Id(activeConfig)) {
-            ALOGE("Setting active config to %d for HWC1 config %u", config->getId(), activeConfig);
-            mActiveConfig = config;
-            if (config->getColorModeForHwc1Id(activeConfig, &mActiveColorMode) != Error::None) {
-                // This should never happen since we checked for the config's presence before
-                // setting it as active.
-                ALOGE("Unable to find color mode for active HWC1 config %d", config->getId());
-                mActiveColorMode = HAL_COLOR_MODE_NATIVE;
-            }
-            break;
-        }
-    }
-    if (!mActiveConfig) {
-        ALOGV("Unable to find active HWC1 config %u, defaulting to "
-                "config 0", activeConfig);
-        mActiveConfig = mConfigs[0];
-        mActiveColorMode = HAL_COLOR_MODE_NATIVE;
-    }
-
-
-
-
-}
-
-void HWC2On1Adapter::Display::allocateRequestedContents() {
-    // What needs to be allocated:
-    // 1 hwc_display_contents_1_t
-    // 1 hwc_layer_1_t for each layer
-    // 1 hwc_rect_t for each layer's surfaceDamage
-    // 1 hwc_rect_t for each layer's visibleRegion
-    // 1 hwc_layer_1_t for the framebuffer
-    // 1 hwc_rect_t for the framebuffer's visibleRegion
-
-    // Count # of surfaceDamage
-    size_t numSurfaceDamages = 0;
-    for (const auto& layer : mLayers) {
-        numSurfaceDamages += layer->getNumSurfaceDamages();
-    }
-
-    // Count # of visibleRegions (start at 1 for mandatory framebuffer target
-    // region)
-    size_t numVisibleRegion = 1;
-    for (const auto& layer : mLayers) {
-        numVisibleRegion += layer->getNumVisibleRegions();
-    }
-
-    size_t numRects = numVisibleRegion + numSurfaceDamages;
-    auto numLayers = mLayers.size() + 1;
-    size_t size = sizeof(hwc_display_contents_1_t) +
-            sizeof(hwc_layer_1_t) * numLayers +
-            sizeof(hwc_rect_t) * numRects;
-    auto contents = static_cast<hwc_display_contents_1_t*>(std::calloc(size, 1));
-    mHwc1RequestedContents.reset(contents);
-    mNextAvailableRect = reinterpret_cast<hwc_rect_t*>(&contents->hwLayers[numLayers]);
-    mNumAvailableRects = numRects;
-}
-
-void HWC2On1Adapter::Display::assignHwc1LayerIds() {
-    mHwc1LayerMap.clear();
-    size_t nextHwc1Id = 0;
-    for (auto& layer : mLayers) {
-        mHwc1LayerMap[nextHwc1Id] = layer;
-        layer->setHwc1Id(nextHwc1Id++);
-    }
-}
-
-void HWC2On1Adapter::Display::updateTypeChanges(const hwc_layer_1_t& hwc1Layer,
-        const Layer& layer) {
-    auto layerId = layer.getId();
-    switch (hwc1Layer.compositionType) {
-        case HWC_FRAMEBUFFER:
-            if (layer.getCompositionType() != Composition::Client) {
-                mChanges->addTypeChange(layerId, Composition::Client);
-            }
-            break;
-        case HWC_OVERLAY:
-            if (layer.getCompositionType() != Composition::Device) {
-                mChanges->addTypeChange(layerId, Composition::Device);
-            }
-            break;
-        case HWC_BACKGROUND:
-            ALOGE_IF(layer.getCompositionType() != Composition::SolidColor,
-                    "updateTypeChanges: HWC1 requested BACKGROUND, but HWC2"
-                    " wasn't expecting SolidColor");
-            break;
-        case HWC_FRAMEBUFFER_TARGET:
-            // Do nothing, since it shouldn't be modified by HWC1
-            break;
-        case HWC_SIDEBAND:
-            ALOGE_IF(layer.getCompositionType() != Composition::Sideband,
-                    "updateTypeChanges: HWC1 requested SIDEBAND, but HWC2"
-                    " wasn't expecting Sideband");
-            break;
-        case HWC_CURSOR_OVERLAY:
-            ALOGE_IF(layer.getCompositionType() != Composition::Cursor,
-                    "updateTypeChanges: HWC1 requested CURSOR_OVERLAY, but"
-                    " HWC2 wasn't expecting Cursor");
-            break;
-    }
-}
-
-void HWC2On1Adapter::Display::updateLayerRequests(
-        const hwc_layer_1_t& hwc1Layer, const Layer& layer) {
-    if ((hwc1Layer.hints & HWC_HINT_CLEAR_FB) != 0) {
-        mChanges->addLayerRequest(layer.getId(),
-                LayerRequest::ClearClientTarget);
-    }
-}
-
-void HWC2On1Adapter::Display::prepareFramebufferTarget() {
-    // We check that mActiveConfig is valid in Display::prepare
-    int32_t width = mActiveConfig->getAttribute(Attribute::Width);
-    int32_t height = mActiveConfig->getAttribute(Attribute::Height);
-
-    auto& hwc1Target = mHwc1RequestedContents->hwLayers[mLayers.size()];
-    hwc1Target.compositionType = HWC_FRAMEBUFFER_TARGET;
-    hwc1Target.releaseFenceFd = -1;
-    hwc1Target.hints = 0;
-    hwc1Target.flags = 0;
-    hwc1Target.transform = 0;
-    hwc1Target.blending = HWC_BLENDING_PREMULT;
-    if (mDevice.getHwc1MinorVersion() < 3) {
-        hwc1Target.sourceCropi = {0, 0, width, height};
-    } else {
-        hwc1Target.sourceCropf = {0.0f, 0.0f, static_cast<float>(width),
-                static_cast<float>(height)};
-    }
-    hwc1Target.displayFrame = {0, 0, width, height};
-    hwc1Target.planeAlpha = 255;
-
-    hwc1Target.visibleRegionScreen.numRects = 1;
-    hwc_rect_t* rects = GetRects(1);
-    rects[0].left = 0;
-    rects[0].top = 0;
-    rects[0].right = width;
-    rects[0].bottom = height;
-    hwc1Target.visibleRegionScreen.rects = rects;
-
-    // We will set this to the correct value in set
-    hwc1Target.acquireFenceFd = -1;
-}
-
-// Layer functions
-
-std::atomic<hwc2_layer_t> HWC2On1Adapter::Layer::sNextId(1);
-
-HWC2On1Adapter::Layer::Layer(Display& display)
-  : mId(sNextId++),
-    mDisplay(display),
-    mBuffer(),
-    mSurfaceDamage(),
-    mBlendMode(BlendMode::None),
-    mColor({0, 0, 0, 0}),
-    mCompositionType(Composition::Invalid),
-    mDisplayFrame({0, 0, -1, -1}),
-    mPlaneAlpha(0.0f),
-    mSidebandStream(nullptr),
-    mSourceCrop({0.0f, 0.0f, -1.0f, -1.0f}),
-    mTransform(Transform::None),
-    mVisibleRegion(),
-    mZ(0),
-    mReleaseFence(),
-    mHwc1Id(0),
-    mHasUnsupportedPlaneAlpha(false) {}
-
-bool HWC2On1Adapter::SortLayersByZ::operator()(
-        const std::shared_ptr<Layer>& lhs, const std::shared_ptr<Layer>& rhs) {
-    return lhs->getZ() < rhs->getZ();
-}
-
-Error HWC2On1Adapter::Layer::setBuffer(buffer_handle_t buffer,
-        int32_t acquireFence) {
-    ALOGV("Setting acquireFence to %d for layer %" PRIu64, acquireFence, mId);
-    mBuffer.setBuffer(buffer);
-    mBuffer.setFence(acquireFence);
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Layer::setCursorPosition(int32_t x, int32_t y) {
-    if (mCompositionType != Composition::Cursor) {
-        return Error::BadLayer;
-    }
-
-    if (mDisplay.hasChanges()) {
-        return Error::NotValidated;
-    }
-
-    auto displayId = mDisplay.getHwc1Id();
-    auto hwc1Device = mDisplay.getDevice().getHwc1Device();
-    hwc1Device->setCursorPositionAsync(hwc1Device, displayId, x, y);
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Layer::setSurfaceDamage(hwc_region_t damage) {
-    // HWC1 supports surface damage starting only with version 1.5.
-    if (mDisplay.getDevice().mHwc1MinorVersion < 5) {
-        return Error::None;
-    }
-    mSurfaceDamage.resize(damage.numRects);
-    std::copy_n(damage.rects, damage.numRects, mSurfaceDamage.begin());
-    return Error::None;
-}
-
-// Layer state functions
-
-Error HWC2On1Adapter::Layer::setBlendMode(BlendMode mode) {
-    mBlendMode = mode;
-    mDisplay.markGeometryChanged();
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Layer::setColor(hwc_color_t color) {
-    mColor = color;
-    mDisplay.markGeometryChanged();
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Layer::setCompositionType(Composition type) {
-    mCompositionType = type;
-    mDisplay.markGeometryChanged();
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Layer::setDataspace(android_dataspace_t) {
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Layer::setDisplayFrame(hwc_rect_t frame) {
-    mDisplayFrame = frame;
-    mDisplay.markGeometryChanged();
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Layer::setPlaneAlpha(float alpha) {
-    mPlaneAlpha = alpha;
-    mDisplay.markGeometryChanged();
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Layer::setSidebandStream(const native_handle_t* stream) {
-    mSidebandStream = stream;
-    mDisplay.markGeometryChanged();
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Layer::setSourceCrop(hwc_frect_t crop) {
-    mSourceCrop = crop;
-    mDisplay.markGeometryChanged();
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Layer::setTransform(Transform transform) {
-    mTransform = transform;
-    mDisplay.markGeometryChanged();
-    return Error::None;
-}
-
-static bool compareRects(const hwc_rect_t& rect1, const hwc_rect_t& rect2) {
-    return rect1.left == rect2.left &&
-            rect1.right == rect2.right &&
-            rect1.top == rect2.top &&
-            rect1.bottom == rect2.bottom;
-}
-
-Error HWC2On1Adapter::Layer::setVisibleRegion(hwc_region_t visible) {
-    if ((getNumVisibleRegions() != visible.numRects) ||
-        !std::equal(mVisibleRegion.begin(), mVisibleRegion.end(), visible.rects,
-                    compareRects)) {
-        mVisibleRegion.resize(visible.numRects);
-        std::copy_n(visible.rects, visible.numRects, mVisibleRegion.begin());
-        mDisplay.markGeometryChanged();
-    }
-    return Error::None;
-}
-
-Error HWC2On1Adapter::Layer::setZ(uint32_t z) {
-    mZ = z;
-    return Error::None;
-}
-
-void HWC2On1Adapter::Layer::addReleaseFence(int fenceFd) {
-    ALOGV("addReleaseFence %d to layer %" PRIu64, fenceFd, mId);
-    mReleaseFence.add(fenceFd);
-}
-
-const sp<MiniFence>& HWC2On1Adapter::Layer::getReleaseFence() const {
-    return mReleaseFence.get();
-}
-
-void HWC2On1Adapter::Layer::applyState(hwc_layer_1_t& hwc1Layer) {
-    applyCommonState(hwc1Layer);
-    applyCompositionType(hwc1Layer);
-    switch (mCompositionType) {
-        case Composition::SolidColor : applySolidColorState(hwc1Layer); break;
-        case Composition::Sideband : applySidebandState(hwc1Layer); break;
-        default: applyBufferState(hwc1Layer); break;
-    }
-}
-
-static std::string regionStrings(const std::vector<hwc_rect_t>& visibleRegion,
-        const std::vector<hwc_rect_t>& surfaceDamage) {
-    std::string regions;
-    regions += "        Visible Region";
-    regions.resize(40, ' ');
-    regions += "Surface Damage\n";
-
-    size_t numPrinted = 0;
-    size_t maxSize = std::max(visibleRegion.size(), surfaceDamage.size());
-    while (numPrinted < maxSize) {
-        std::string line("        ");
-        if (visibleRegion.empty() && numPrinted == 0) {
-            line += "None";
-        } else if (numPrinted < visibleRegion.size()) {
-            line += rectString(visibleRegion[numPrinted]);
-        }
-        line.resize(40, ' ');
-        if (surfaceDamage.empty() && numPrinted == 0) {
-            line += "None";
-        } else if (numPrinted < surfaceDamage.size()) {
-            line += rectString(surfaceDamage[numPrinted]);
-        }
-        line += '\n';
-        regions += line;
-        ++numPrinted;
-    }
-    return regions;
-}
-
-std::string HWC2On1Adapter::Layer::dump() const {
-    std::stringstream output;
-    const char* fill = "      ";
-
-    output << fill << to_string(mCompositionType);
-    output << " Layer  HWC2/1: " << mId << "/" << mHwc1Id << "  ";
-    output << "Z: " << mZ;
-    if (mCompositionType == HWC2::Composition::SolidColor) {
-        output << "  " << colorString(mColor);
-    } else if (mCompositionType == HWC2::Composition::Sideband) {
-        output << "  Handle: " << mSidebandStream << '\n';
-    } else {
-        output << "  Buffer: " << mBuffer.getBuffer() << "/" <<
-                mBuffer.getFence() << '\n';
-        output << fill << "  Display frame [LTRB]: " <<
-                rectString(mDisplayFrame) << '\n';
-        output << fill << "  Source crop: " <<
-                frectString(mSourceCrop) << '\n';
-        output << fill << "  Transform: " << to_string(mTransform);
-        output << "  Blend mode: " << to_string(mBlendMode);
-        if (mPlaneAlpha != 1.0f) {
-            output << "  Alpha: " <<
-                alphaString(mPlaneAlpha) << '\n';
-        } else {
-            output << '\n';
-        }
-        output << regionStrings(mVisibleRegion, mSurfaceDamage);
-    }
-    return output.str();
-}
-
-static int getHwc1Blending(HWC2::BlendMode blendMode) {
-    switch (blendMode) {
-        case BlendMode::Coverage: return HWC_BLENDING_COVERAGE;
-        case BlendMode::Premultiplied: return HWC_BLENDING_PREMULT;
-        default: return HWC_BLENDING_NONE;
-    }
-}
-
-void HWC2On1Adapter::Layer::applyCommonState(hwc_layer_1_t& hwc1Layer) {
-    auto minorVersion = mDisplay.getDevice().getHwc1MinorVersion();
-    hwc1Layer.blending = getHwc1Blending(mBlendMode);
-    hwc1Layer.displayFrame = mDisplayFrame;
-
-    auto pendingAlpha = mPlaneAlpha;
-    if (minorVersion < 2) {
-        mHasUnsupportedPlaneAlpha = pendingAlpha < 1.0f;
-    } else {
-        hwc1Layer.planeAlpha =
-                static_cast<uint8_t>(255.0f * pendingAlpha + 0.5f);
-    }
-
-    if (minorVersion < 3) {
-        auto pending = mSourceCrop;
-        hwc1Layer.sourceCropi.left =
-                static_cast<int32_t>(std::ceil(pending.left));
-        hwc1Layer.sourceCropi.top =
-                static_cast<int32_t>(std::ceil(pending.top));
-        hwc1Layer.sourceCropi.right =
-                static_cast<int32_t>(std::floor(pending.right));
-        hwc1Layer.sourceCropi.bottom =
-                static_cast<int32_t>(std::floor(pending.bottom));
-    } else {
-        hwc1Layer.sourceCropf = mSourceCrop;
-    }
-
-    hwc1Layer.transform = static_cast<uint32_t>(mTransform);
-
-    auto& hwc1VisibleRegion = hwc1Layer.visibleRegionScreen;
-    hwc1VisibleRegion.numRects = mVisibleRegion.size();
-    hwc_rect_t* rects = mDisplay.GetRects(hwc1VisibleRegion.numRects);
-    hwc1VisibleRegion.rects = rects;
-    for (size_t i = 0; i < mVisibleRegion.size(); i++) {
-        rects[i] = mVisibleRegion[i];
-    }
-}
-
-void HWC2On1Adapter::Layer::applySolidColorState(hwc_layer_1_t& hwc1Layer) {
-    // If the device does not support background color it is likely to make
-    // assumption regarding backgroundColor and handle (both fields occupy
-    // the same location in hwc_layer_1_t union).
-    // To not confuse these devices we don't set background color and we
-    // make sure handle is a null pointer.
-    if (hasUnsupportedBackgroundColor()) {
-        hwc1Layer.handle = nullptr;
-    } else {
-        hwc1Layer.backgroundColor = mColor;
-    }
-}
-
-void HWC2On1Adapter::Layer::applySidebandState(hwc_layer_1_t& hwc1Layer) {
-    hwc1Layer.sidebandStream = mSidebandStream;
-}
-
-void HWC2On1Adapter::Layer::applyBufferState(hwc_layer_1_t& hwc1Layer) {
-    hwc1Layer.handle = mBuffer.getBuffer();
-    hwc1Layer.acquireFenceFd = mBuffer.getFence();
-}
-
-void HWC2On1Adapter::Layer::applyCompositionType(hwc_layer_1_t& hwc1Layer) {
-    // HWC1 never supports color transforms or dataspaces and only sometimes
-    // supports plane alpha (depending on the version). These require us to drop
-    // some or all layers to client composition.
-    if (mHasUnsupportedPlaneAlpha || mDisplay.hasColorTransform() ||
-            hasUnsupportedBackgroundColor()) {
-        hwc1Layer.compositionType = HWC_FRAMEBUFFER;
-        hwc1Layer.flags = HWC_SKIP_LAYER;
-        return;
-    }
-
-    hwc1Layer.flags = 0;
-    switch (mCompositionType) {
-        case Composition::Client:
-            hwc1Layer.compositionType = HWC_FRAMEBUFFER;
-            hwc1Layer.flags |= HWC_SKIP_LAYER;
-            break;
-        case Composition::Device:
-            hwc1Layer.compositionType = HWC_FRAMEBUFFER;
-            break;
-        case Composition::SolidColor:
-            // In theory the following line should work, but since the HWC1
-            // version of SurfaceFlinger never used HWC_BACKGROUND, HWC1
-            // devices may not work correctly. To be on the safe side, we
-            // fall back to client composition.
-            //
-            // hwc1Layer.compositionType = HWC_BACKGROUND;
-            hwc1Layer.compositionType = HWC_FRAMEBUFFER;
-            hwc1Layer.flags |= HWC_SKIP_LAYER;
-            break;
-        case Composition::Cursor:
-            hwc1Layer.compositionType = HWC_FRAMEBUFFER;
-            if (mDisplay.getDevice().getHwc1MinorVersion() >= 4) {
-                hwc1Layer.hints |= HWC_IS_CURSOR_LAYER;
-            }
-            break;
-        case Composition::Sideband:
-            if (mDisplay.getDevice().getHwc1MinorVersion() < 4) {
-                hwc1Layer.compositionType = HWC_SIDEBAND;
-            } else {
-                hwc1Layer.compositionType = HWC_FRAMEBUFFER;
-                hwc1Layer.flags |= HWC_SKIP_LAYER;
-            }
-            break;
-        default:
-            hwc1Layer.compositionType = HWC_FRAMEBUFFER;
-            hwc1Layer.flags |= HWC_SKIP_LAYER;
-            break;
-    }
-    ALOGV("Layer %" PRIu64 " %s set to %d", mId,
-            to_string(mCompositionType).c_str(),
-            hwc1Layer.compositionType);
-    ALOGV_IF(hwc1Layer.flags & HWC_SKIP_LAYER, "    and skipping");
-}
-
-// Adapter helpers
-
-void HWC2On1Adapter::populateCapabilities() {
-    if (mHwc1MinorVersion >= 3U) {
-        int supportedTypes = 0;
-        auto result = mHwc1Device->query(mHwc1Device,
-                HWC_DISPLAY_TYPES_SUPPORTED, &supportedTypes);
-        if ((result == 0) && ((supportedTypes & HWC_DISPLAY_VIRTUAL_BIT) != 0)) {
-            ALOGI("Found support for HWC virtual displays");
-            mHwc1SupportsVirtualDisplays = true;
-        }
-    }
-    if (mHwc1MinorVersion >= 4U) {
-        mCapabilities.insert(Capability::SidebandStream);
-    }
-
-    // Check for HWC background color layer support.
-    if (mHwc1MinorVersion >= 1U) {
-        int backgroundColorSupported = 0;
-        auto result = mHwc1Device->query(mHwc1Device,
-                                         HWC_BACKGROUND_LAYER_SUPPORTED,
-                                         &backgroundColorSupported);
-        if ((result == 0) && (backgroundColorSupported == 1)) {
-            ALOGV("Found support for HWC background color");
-            mHwc1SupportsBackgroundColor = true;
-        }
-    }
-
-    // Some devices might have HWC1 retire fences that accurately emulate
-    // HWC2 present fences when they are deferred, but it's not very reliable.
-    // To be safe, we indicate PresentFenceIsNotReliable for all HWC1 devices.
-    mCapabilities.insert(Capability::PresentFenceIsNotReliable);
-}
-
-HWC2On1Adapter::Display* HWC2On1Adapter::getDisplay(hwc2_display_t id) {
-    std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
-
-    auto display = mDisplays.find(id);
-    if (display == mDisplays.end()) {
-        return nullptr;
-    }
-
-    return display->second.get();
-}
-
-std::tuple<HWC2On1Adapter::Layer*, Error> HWC2On1Adapter::getLayer(
-        hwc2_display_t displayId, hwc2_layer_t layerId) {
-    auto display = getDisplay(displayId);
-    if (!display) {
-        return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadDisplay);
-    }
-
-    auto layerEntry = mLayers.find(layerId);
-    if (layerEntry == mLayers.end()) {
-        return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadLayer);
-    }
-
-    auto layer = layerEntry->second;
-    if (layer->getDisplay().getId() != displayId) {
-        return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadLayer);
-    }
-    return std::make_tuple(layer.get(), Error::None);
-}
-
-void HWC2On1Adapter::populatePrimary() {
-    std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
-
-    auto display = std::make_shared<Display>(*this, HWC2::DisplayType::Physical);
-    mHwc1DisplayMap[HWC_DISPLAY_PRIMARY] = display->getId();
-    display->setHwc1Id(HWC_DISPLAY_PRIMARY);
-    display->populateConfigs();
-    mDisplays.emplace(display->getId(), std::move(display));
-}
-
-bool HWC2On1Adapter::prepareAllDisplays() {
-    ATRACE_CALL();
-
-    std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
-
-    for (const auto& displayPair : mDisplays) {
-        auto& display = displayPair.second;
-        if (!display->prepare()) {
-            return false;
-        }
-    }
-
-    if (mHwc1DisplayMap.count(HWC_DISPLAY_PRIMARY) == 0) {
-        ALOGE("prepareAllDisplays: Unable to find primary HWC1 display");
-        return false;
-    }
-
-    // Build an array of hwc_display_contents_1 to call prepare() on HWC1.
-    mHwc1Contents.clear();
-
-    // Always push the primary display
-    auto primaryDisplayId = mHwc1DisplayMap[HWC_DISPLAY_PRIMARY];
-    auto& primaryDisplay = mDisplays[primaryDisplayId];
-    mHwc1Contents.push_back(primaryDisplay->getDisplayContents());
-
-    // Push the external display, if present
-    if (mHwc1DisplayMap.count(HWC_DISPLAY_EXTERNAL) != 0) {
-        auto externalDisplayId = mHwc1DisplayMap[HWC_DISPLAY_EXTERNAL];
-        auto& externalDisplay = mDisplays[externalDisplayId];
-        mHwc1Contents.push_back(externalDisplay->getDisplayContents());
-    } else {
-        // Even if an external display isn't present, we still need to send
-        // at least two displays down to HWC1
-        mHwc1Contents.push_back(nullptr);
-    }
-
-    // Push the hardware virtual display, if supported and present
-    if (mHwc1MinorVersion >= 3) {
-        if (mHwc1DisplayMap.count(HWC_DISPLAY_VIRTUAL) != 0) {
-            auto virtualDisplayId = mHwc1DisplayMap[HWC_DISPLAY_VIRTUAL];
-            auto& virtualDisplay = mDisplays[virtualDisplayId];
-            mHwc1Contents.push_back(virtualDisplay->getDisplayContents());
-        } else {
-            mHwc1Contents.push_back(nullptr);
-        }
-    }
-
-    for (auto& displayContents : mHwc1Contents) {
-        if (!displayContents) {
-            continue;
-        }
-
-        ALOGV("Display %zd layers:", mHwc1Contents.size() - 1);
-        for (size_t l = 0; l < displayContents->numHwLayers; ++l) {
-            auto& layer = displayContents->hwLayers[l];
-            ALOGV("  %zd: %d", l, layer.compositionType);
-        }
-    }
-
-    ALOGV("Calling HWC1 prepare");
-    {
-        ATRACE_NAME("HWC1 prepare");
-        mHwc1Device->prepare(mHwc1Device, mHwc1Contents.size(),
-                mHwc1Contents.data());
-    }
-
-    for (size_t c = 0; c < mHwc1Contents.size(); ++c) {
-        auto& contents = mHwc1Contents[c];
-        if (!contents) {
-            continue;
-        }
-        ALOGV("Display %zd layers:", c);
-        for (size_t l = 0; l < contents->numHwLayers; ++l) {
-            ALOGV("  %zd: %d", l, contents->hwLayers[l].compositionType);
-        }
-    }
-
-    // Return the received contents to their respective displays
-    for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) {
-        if (mHwc1Contents[hwc1Id] == nullptr) {
-            continue;
-        }
-
-        auto displayId = mHwc1DisplayMap[hwc1Id];
-        auto& display = mDisplays[displayId];
-        display->generateChanges();
-    }
-
-    return true;
-}
-
-void dumpHWC1Message(hwc_composer_device_1* device, size_t numDisplays,
-                     hwc_display_contents_1_t** displays) {
-    ALOGV("*****************************");
-    size_t displayId = 0;
-    while (displayId < numDisplays) {
-        hwc_display_contents_1_t* display = displays[displayId];
-
-        ALOGV("hwc_display_contents_1_t[%zu] @0x%p", displayId, display);
-        if (display == nullptr) {
-            displayId++;
-            continue;
-        }
-        ALOGV("  retirefd:0x%08x", display->retireFenceFd);
-        ALOGV("  outbuf  :0x%p", display->outbuf);
-        ALOGV("  outbuffd:0x%08x", display->outbufAcquireFenceFd);
-        ALOGV("  flags   :0x%08x", display->flags);
-        for(size_t layerId=0 ; layerId < display->numHwLayers ; layerId++) {
-            hwc_layer_1_t& layer = display->hwLayers[layerId];
-            ALOGV("    Layer[%zu]:", layerId);
-            ALOGV("      composition        : 0x%08x", layer.compositionType);
-            ALOGV("      hints              : 0x%08x", layer.hints);
-            ALOGV("      flags              : 0x%08x", layer.flags);
-            ALOGV("      handle             : 0x%p", layer.handle);
-            ALOGV("      transform          : 0x%08x", layer.transform);
-            ALOGV("      blending           : 0x%08x", layer.blending);
-            ALOGV("      sourceCropf        : %f, %f, %f, %f",
-                  layer.sourceCropf.left,
-                  layer.sourceCropf.top,
-                  layer.sourceCropf.right,
-                  layer.sourceCropf.bottom);
-            ALOGV("      displayFrame       : %d, %d, %d, %d",
-                  layer.displayFrame.left,
-                  layer.displayFrame.left,
-                  layer.displayFrame.left,
-                  layer.displayFrame.left);
-            hwc_region_t& visReg = layer.visibleRegionScreen;
-            ALOGV("      visibleRegionScreen: #0x%08zx[@0x%p]",
-                  visReg.numRects,
-                  visReg.rects);
-            for (size_t visRegId=0; visRegId < visReg.numRects ; visRegId++) {
-                if (layer.visibleRegionScreen.rects == nullptr) {
-                    ALOGV("        null");
-                } else {
-                    ALOGV("        visibleRegionScreen[%zu] %d, %d, %d, %d",
-                          visRegId,
-                          visReg.rects[visRegId].left,
-                          visReg.rects[visRegId].top,
-                          visReg.rects[visRegId].right,
-                          visReg.rects[visRegId].bottom);
-                }
-            }
-            ALOGV("      acquireFenceFd     : 0x%08x", layer.acquireFenceFd);
-            ALOGV("      releaseFenceFd     : 0x%08x", layer.releaseFenceFd);
-            ALOGV("      planeAlpha         : 0x%08x", layer.planeAlpha);
-            if (getMinorVersion(device) < 5)
-               continue;
-            ALOGV("      surfaceDamage      : #0x%08zx[@0x%p]",
-                  layer.surfaceDamage.numRects,
-                  layer.surfaceDamage.rects);
-            for (size_t sdId=0; sdId < layer.surfaceDamage.numRects ; sdId++) {
-                if (layer.surfaceDamage.rects == nullptr) {
-                    ALOGV("      null");
-                } else {
-                    ALOGV("      surfaceDamage[%zu] %d, %d, %d, %d",
-                          sdId,
-                          layer.surfaceDamage.rects[sdId].left,
-                          layer.surfaceDamage.rects[sdId].top,
-                          layer.surfaceDamage.rects[sdId].right,
-                          layer.surfaceDamage.rects[sdId].bottom);
-                }
-            }
-        }
-        displayId++;
-    }
-    ALOGV("-----------------------------");
-}
-
-Error HWC2On1Adapter::setAllDisplays() {
-    ATRACE_CALL();
-
-    std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
-
-    // Make sure we're ready to validate
-    for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) {
-        if (mHwc1Contents[hwc1Id] == nullptr) {
-            continue;
-        }
-
-        auto displayId = mHwc1DisplayMap[hwc1Id];
-        auto& display = mDisplays[displayId];
-        Error error = display->set(*mHwc1Contents[hwc1Id]);
-        if (error != Error::None) {
-            ALOGE("setAllDisplays: Failed to set display %zd: %s", hwc1Id,
-                    to_string(error).c_str());
-            return error;
-        }
-    }
-
-    ALOGV("Calling HWC1 set");
-    {
-        ATRACE_NAME("HWC1 set");
-        //dumpHWC1Message(mHwc1Device, mHwc1Contents.size(), mHwc1Contents.data());
-        mHwc1Device->set(mHwc1Device, mHwc1Contents.size(),
-                mHwc1Contents.data());
-    }
-
-    // Add retire and release fences
-    for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) {
-        if (mHwc1Contents[hwc1Id] == nullptr) {
-            continue;
-        }
-
-        auto displayId = mHwc1DisplayMap[hwc1Id];
-        auto& display = mDisplays[displayId];
-        auto retireFenceFd = mHwc1Contents[hwc1Id]->retireFenceFd;
-        ALOGV("setAllDisplays: Adding retire fence %d to display %zd",
-                retireFenceFd, hwc1Id);
-        display->addRetireFence(mHwc1Contents[hwc1Id]->retireFenceFd);
-        display->addReleaseFences(*mHwc1Contents[hwc1Id]);
-    }
-
-    return Error::None;
-}
-
-void HWC2On1Adapter::hwc1Invalidate() {
-    ALOGV("Received hwc1Invalidate");
-
-    std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
-
-    // If the HWC2-side callback hasn't been registered yet, buffer this until
-    // it is registered.
-    if (mCallbacks.count(Callback::Refresh) == 0) {
-        mHasPendingInvalidate = true;
-        return;
-    }
-
-    const auto& callbackInfo = mCallbacks[Callback::Refresh];
-    std::vector<hwc2_display_t> displays;
-    for (const auto& displayPair : mDisplays) {
-        displays.emplace_back(displayPair.first);
-    }
-
-    // Call back without the state lock held.
-    lock.unlock();
-
-    auto refresh = reinterpret_cast<HWC2_PFN_REFRESH>(callbackInfo.pointer);
-    for (auto display : displays) {
-        refresh(callbackInfo.data, display);
-    }
-}
-
-void HWC2On1Adapter::hwc1Vsync(int hwc1DisplayId, int64_t timestamp) {
-    ALOGV("Received hwc1Vsync(%d, %" PRId64 ")", hwc1DisplayId, timestamp);
-
-    std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
-
-    // If the HWC2-side callback hasn't been registered yet, buffer this until
-    // it is registered.
-    if (mCallbacks.count(Callback::Vsync) == 0) {
-        mPendingVsyncs.emplace_back(hwc1DisplayId, timestamp);
-        return;
-    }
-
-    if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
-        ALOGE("hwc1Vsync: Couldn't find display for HWC1 id %d", hwc1DisplayId);
-        return;
-    }
-
-    const auto& callbackInfo = mCallbacks[Callback::Vsync];
-    auto displayId = mHwc1DisplayMap[hwc1DisplayId];
-
-    // Call back without the state lock held.
-    lock.unlock();
-
-    auto vsync = reinterpret_cast<HWC2_PFN_VSYNC>(callbackInfo.pointer);
-    vsync(callbackInfo.data, displayId, timestamp);
-}
-
-void HWC2On1Adapter::hwc1Hotplug(int hwc1DisplayId, int connected) {
-    ALOGV("Received hwc1Hotplug(%d, %d)", hwc1DisplayId, connected);
-
-    if (hwc1DisplayId != HWC_DISPLAY_EXTERNAL) {
-        ALOGE("hwc1Hotplug: Received hotplug for non-external display");
-        return;
-    }
-
-    std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
-
-    // If the HWC2-side callback hasn't been registered yet, buffer this until
-    // it is registered
-    if (mCallbacks.count(Callback::Hotplug) == 0) {
-        mPendingHotplugs.emplace_back(hwc1DisplayId, connected);
-        return;
-    }
-
-    hwc2_display_t displayId = UINT64_MAX;
-    if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
-        if (connected == 0) {
-            ALOGW("hwc1Hotplug: Received disconnect for unconnected display");
-            return;
-        }
-
-        // Create a new display on connect
-        auto display = std::make_shared<HWC2On1Adapter::Display>(*this,
-                HWC2::DisplayType::Physical);
-        display->setHwc1Id(HWC_DISPLAY_EXTERNAL);
-        display->populateConfigs();
-        displayId = display->getId();
-        mHwc1DisplayMap[HWC_DISPLAY_EXTERNAL] = displayId;
-        mDisplays.emplace(displayId, std::move(display));
-    } else {
-        if (connected != 0) {
-            ALOGW("hwc1Hotplug: Received connect for previously connected "
-                    "display");
-            return;
-        }
-
-        // Disconnect an existing display
-        displayId = mHwc1DisplayMap[hwc1DisplayId];
-        mHwc1DisplayMap.erase(HWC_DISPLAY_EXTERNAL);
-        mDisplays.erase(displayId);
-    }
-
-    const auto& callbackInfo = mCallbacks[Callback::Hotplug];
-
-    // Call back without the state lock held
-    lock.unlock();
-
-    auto hotplug = reinterpret_cast<HWC2_PFN_HOTPLUG>(callbackInfo.pointer);
-    auto hwc2Connected = (connected == 0) ?
-            HWC2::Connection::Disconnected : HWC2::Connection::Connected;
-    hotplug(callbackInfo.data, displayId, static_cast<int32_t>(hwc2Connected));
-}
-} // namespace android
diff --git a/libs/hwc2on1adapter/MiniFence.cpp b/libs/hwc2on1adapter/MiniFence.cpp
deleted file mode 100644
index dfbe4d6..0000000
--- a/libs/hwc2on1adapter/MiniFence.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "hwc2on1adapter/MiniFence.h"
-
-#include <unistd.h>
-
-namespace android {
-
-const sp<MiniFence> MiniFence::NO_FENCE = sp<MiniFence>(new MiniFence);
-
-MiniFence::MiniFence() :
-    mFenceFd(-1) {
-}
-
-MiniFence::MiniFence(int fenceFd) :
-    mFenceFd(fenceFd) {
-}
-
-MiniFence::~MiniFence() {
-    if (mFenceFd != -1) {
-        close(mFenceFd);
-    }
-}
-
-int MiniFence::dup() const {
-    return ::dup(mFenceFd);
-}
-}
diff --git a/libs/hwc2on1adapter/include/hwc2on1adapter/HWC2On1Adapter.h b/libs/hwc2on1adapter/include/hwc2on1adapter/HWC2On1Adapter.h
deleted file mode 100644
index 3badfce..0000000
--- a/libs/hwc2on1adapter/include/hwc2on1adapter/HWC2On1Adapter.h
+++ /dev/null
@@ -1,738 +0,0 @@
-/*
- * Copyright 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_SF_HWC2_ON_1_ADAPTER_H
-#define ANDROID_SF_HWC2_ON_1_ADAPTER_H
-
-#define HWC2_INCLUDE_STRINGIFICATION
-#define HWC2_USE_CPP11
-#include <hardware/hwcomposer2.h>
-#undef HWC2_INCLUDE_STRINGIFICATION
-#undef HWC2_USE_CPP11
-
-#include "MiniFence.h"
-
-#include <atomic>
-#include <map>
-#include <mutex>
-#include <queue>
-#include <set>
-#include <unordered_map>
-#include <unordered_set>
-#include <vector>
-
-struct hwc_composer_device_1;
-struct hwc_display_contents_1;
-struct hwc_layer_1;
-
-namespace android {
-
-// For devices unable to provide an implementation of HWC2 (see hwcomposer2.h),
-// we provide an adapter able to talk to HWC1 (see hwcomposer.h). It translates
-// streamed function calls ala HWC2 model to batched array of structs calls ala
-// HWC1 model.
-class HWC2On1Adapter : public hwc2_device_t
-{
-public:
-    explicit HWC2On1Adapter(struct hwc_composer_device_1* hwc1Device);
-    ~HWC2On1Adapter();
-
-    struct hwc_composer_device_1* getHwc1Device() const { return mHwc1Device; }
-    uint8_t getHwc1MinorVersion() const { return mHwc1MinorVersion; }
-
-private:
-    static inline HWC2On1Adapter* getAdapter(hwc2_device_t* device) {
-        return static_cast<HWC2On1Adapter*>(device);
-    }
-
-    // getCapabilities
-
-    void doGetCapabilities(uint32_t* outCount,
-            int32_t* /*hwc2_capability_t*/ outCapabilities);
-    static void getCapabilitiesHook(hwc2_device_t* device, uint32_t* outCount,
-            int32_t* /*hwc2_capability_t*/ outCapabilities) {
-        getAdapter(device)->doGetCapabilities(outCount, outCapabilities);
-    }
-
-    bool supportsBackgroundColor() {
-        return mHwc1SupportsBackgroundColor;
-    }
-
-    // getFunction
-
-    hwc2_function_pointer_t doGetFunction(HWC2::FunctionDescriptor descriptor);
-    static hwc2_function_pointer_t getFunctionHook(hwc2_device_t* device,
-            int32_t intDesc) {
-        auto descriptor = static_cast<HWC2::FunctionDescriptor>(intDesc);
-        return getAdapter(device)->doGetFunction(descriptor);
-    }
-
-    // Device functions
-
-    HWC2::Error createVirtualDisplay(uint32_t width, uint32_t height,
-            hwc2_display_t* outDisplay);
-    static int32_t createVirtualDisplayHook(hwc2_device_t* device,
-            uint32_t width, uint32_t height, int32_t* /*format*/,
-            hwc2_display_t* outDisplay) {
-        // HWC1 implementations cannot override the buffer format requested by
-        // the consumer
-        auto error = getAdapter(device)->createVirtualDisplay(width, height,
-                outDisplay);
-        return static_cast<int32_t>(error);
-    }
-
-    HWC2::Error destroyVirtualDisplay(hwc2_display_t display);
-    static int32_t destroyVirtualDisplayHook(hwc2_device_t* device,
-            hwc2_display_t display) {
-        auto error = getAdapter(device)->destroyVirtualDisplay(display);
-        return static_cast<int32_t>(error);
-    }
-
-    std::string mDumpString;
-    void dump(uint32_t* outSize, char* outBuffer);
-    static void dumpHook(hwc2_device_t* device, uint32_t* outSize,
-            char* outBuffer) {
-        getAdapter(device)->dump(outSize, outBuffer);
-    }
-
-    uint32_t getMaxVirtualDisplayCount();
-    static uint32_t getMaxVirtualDisplayCountHook(hwc2_device_t* device) {
-        return getAdapter(device)->getMaxVirtualDisplayCount();
-    }
-
-    HWC2::Error registerCallback(HWC2::Callback descriptor,
-            hwc2_callback_data_t callbackData, hwc2_function_pointer_t pointer);
-    static int32_t registerCallbackHook(hwc2_device_t* device,
-            int32_t intDesc, hwc2_callback_data_t callbackData,
-            hwc2_function_pointer_t pointer) {
-        auto descriptor = static_cast<HWC2::Callback>(intDesc);
-        auto error = getAdapter(device)->registerCallback(descriptor,
-                callbackData, pointer);
-        return static_cast<int32_t>(error);
-    }
-
-    // Display functions
-
-    class Layer;
-
-    class SortLayersByZ {
-        public:
-            bool operator()(const std::shared_ptr<Layer>& lhs,
-                    const std::shared_ptr<Layer>& rhs);
-    };
-
-    // The semantics of the fences returned by the device differ between
-    // hwc1.set() and hwc2.present(). Read hwcomposer.h and hwcomposer2.h
-    // for more information.
-    //
-    // Release fences in hwc1 are obtained on set() for a frame n and signaled
-    // when the layer buffer is not needed for read operations anymore
-    // (typically on frame n+1). In HWC2, release fences are obtained with a
-    // special call after present() for frame n. These fences signal
-    // on frame n: More specifically, the fence for a given buffer provided in
-    // frame n will signal when the prior buffer is no longer required.
-    //
-    // A retire fence (HWC1) is signaled when a composition is replaced
-    // on the panel whereas a present fence (HWC2) is signaled when a
-    // composition starts to be displayed on a panel.
-    //
-    // The HWC2to1Adapter emulates the new fence semantics for a frame
-    // n by returning the fence from frame n-1. For frame 0, the adapter
-    // returns NO_FENCE.
-    class DeferredFence {
-        public:
-            DeferredFence()
-              : mFences({MiniFence::NO_FENCE, MiniFence::NO_FENCE}) {}
-
-            void add(int32_t fenceFd) {
-                mFences.emplace(new MiniFence(fenceFd));
-                mFences.pop();
-            }
-
-            const sp<MiniFence>& get() const {
-                return mFences.front();
-            }
-
-        private:
-            // There are always two fences in this queue.
-            std::queue<sp<MiniFence>> mFences;
-    };
-
-    class FencedBuffer {
-        public:
-            FencedBuffer() : mBuffer(nullptr), mFence(MiniFence::NO_FENCE) {}
-
-            void setBuffer(buffer_handle_t buffer) { mBuffer = buffer; }
-            void setFence(int fenceFd) { mFence = new MiniFence(fenceFd); }
-
-            buffer_handle_t getBuffer() const { return mBuffer; }
-            int getFence() const { return mFence->dup(); }
-
-        private:
-            buffer_handle_t mBuffer;
-            sp<MiniFence> mFence;
-    };
-
-    class Display {
-        public:
-            Display(HWC2On1Adapter& device, HWC2::DisplayType type);
-
-            hwc2_display_t getId() const { return mId; }
-            HWC2On1Adapter& getDevice() const { return mDevice; }
-
-            // Does not require locking because it is set before adding the
-            // Displays to the Adapter's list of displays
-            void setHwc1Id(int32_t id) { mHwc1Id = id; }
-            int32_t getHwc1Id() const { return mHwc1Id; }
-
-            // HWC2 Display functions
-            HWC2::Error acceptChanges();
-            HWC2::Error createLayer(hwc2_layer_t* outLayerId);
-            HWC2::Error destroyLayer(hwc2_layer_t layerId);
-            HWC2::Error getActiveConfig(hwc2_config_t* outConfigId);
-            HWC2::Error getAttribute(hwc2_config_t configId,
-                    HWC2::Attribute attribute, int32_t* outValue);
-            HWC2::Error getChangedCompositionTypes(uint32_t* outNumElements,
-                    hwc2_layer_t* outLayers, int32_t* outTypes);
-            HWC2::Error getColorModes(uint32_t* outNumModes, int32_t* outModes);
-            HWC2::Error getConfigs(uint32_t* outNumConfigs,
-                    hwc2_config_t* outConfigIds);
-            HWC2::Error getDozeSupport(int32_t* outSupport);
-            HWC2::Error getHdrCapabilities(uint32_t* outNumTypes,
-                    int32_t* outTypes, float* outMaxLuminance,
-                    float* outMaxAverageLuminance, float* outMinLuminance);
-            HWC2::Error getName(uint32_t* outSize, char* outName);
-            HWC2::Error getReleaseFences(uint32_t* outNumElements,
-                    hwc2_layer_t* outLayers, int32_t* outFences);
-            HWC2::Error getRequests(int32_t* outDisplayRequests,
-                    uint32_t* outNumElements, hwc2_layer_t* outLayers,
-                    int32_t* outLayerRequests);
-            HWC2::Error getType(int32_t* outType);
-
-            // Since HWC1 "presents" (called "set" in HWC1) all Displays
-            // at once, the first call to any Display::present will trigger
-            // present() on all Displays in the Device. Subsequent calls without
-            // first calling validate() are noop (except for duping/returning
-            // the retire fence).
-            HWC2::Error present(int32_t* outRetireFence);
-
-            HWC2::Error setActiveConfig(hwc2_config_t configId);
-            HWC2::Error setClientTarget(buffer_handle_t target,
-                    int32_t acquireFence, int32_t dataspace,
-                    hwc_region_t damage);
-            HWC2::Error setColorMode(android_color_mode_t mode);
-            HWC2::Error setColorTransform(android_color_transform_t hint);
-            HWC2::Error setOutputBuffer(buffer_handle_t buffer,
-                    int32_t releaseFence);
-            HWC2::Error setPowerMode(HWC2::PowerMode mode);
-            HWC2::Error setVsyncEnabled(HWC2::Vsync enabled);
-
-            // Since HWC1 "validates" (called "prepare" in HWC1) all Displays
-            // at once, the first call to any Display::validate() will trigger
-            // validate() on all other Displays in the Device.
-            HWC2::Error validate(uint32_t* outNumTypes,
-                    uint32_t* outNumRequests);
-
-            HWC2::Error updateLayerZ(hwc2_layer_t layerId, uint32_t z);
-
-            HWC2::Error getClientTargetSupport(uint32_t width, uint32_t height,
-                     int32_t format, int32_t dataspace);
-
-            // Read configs from HWC1 device
-            void populateConfigs();
-
-            // Set configs for a virtual display
-            void populateConfigs(uint32_t width, uint32_t height);
-
-            bool prepare();
-
-            // Called after hwc.prepare() with responses from the device.
-            void generateChanges();
-
-            bool hasChanges() const;
-            HWC2::Error set(hwc_display_contents_1& hwcContents);
-            void addRetireFence(int fenceFd);
-            void addReleaseFences(const hwc_display_contents_1& hwcContents);
-
-            bool hasColorTransform() const;
-
-            std::string dump() const;
-
-            // Return a rect from the pool allocated during validate()
-            hwc_rect_t* GetRects(size_t numRects);
-
-            hwc_display_contents_1* getDisplayContents();
-
-            void markGeometryChanged() { mGeometryChanged = true; }
-            void resetGeometryMarker() { mGeometryChanged = false;}
-        private:
-            class Config {
-                public:
-                    Config(Display& display)
-                      : mDisplay(display),
-                        mId(0),
-                        mAttributes() {}
-
-                    bool isOnDisplay(const Display& display) const {
-                        return display.getId() == mDisplay.getId();
-                    }
-
-                    void setAttribute(HWC2::Attribute attribute, int32_t value);
-                    int32_t getAttribute(HWC2::Attribute attribute) const;
-
-                    void setHwc1Id(uint32_t id);
-                    bool hasHwc1Id(uint32_t id) const;
-                    HWC2::Error getColorModeForHwc1Id(uint32_t id,
-                            android_color_mode_t *outMode) const;
-                    HWC2::Error getHwc1IdForColorMode(android_color_mode_t mode,
-                            uint32_t* outId) const;
-
-                    void setId(hwc2_config_t id) { mId = id; }
-                    hwc2_config_t getId() const { return mId; }
-
-                    // Attempts to merge two configs that differ only in color
-                    // mode. Returns whether the merge was successful
-                    bool merge(const Config& other);
-
-                    std::set<android_color_mode_t> getColorModes() const;
-
-                    // splitLine divides the output into two lines suitable for
-                    // dumpsys SurfaceFlinger
-                    std::string toString(bool splitLine = false) const;
-
-                private:
-                    Display& mDisplay;
-                    hwc2_config_t mId;
-                    std::unordered_map<HWC2::Attribute, int32_t> mAttributes;
-
-                    // Maps from color transform to HWC1 config ID
-                    std::unordered_map<android_color_mode_t, uint32_t> mHwc1Ids;
-            };
-
-            // Stores changes requested from the device upon calling prepare().
-            // Handles change request to:
-            //   - Layer composition type.
-            //   - Layer hints.
-            class Changes {
-                public:
-                    uint32_t getNumTypes() const {
-                        return static_cast<uint32_t>(mTypeChanges.size());
-                    }
-
-                    uint32_t getNumLayerRequests() const {
-                        return static_cast<uint32_t>(mLayerRequests.size());
-                    }
-
-                    const std::unordered_map<hwc2_layer_t, HWC2::Composition>&
-                            getTypeChanges() const {
-                        return mTypeChanges;
-                    }
-
-                    const std::unordered_map<hwc2_layer_t, HWC2::LayerRequest>&
-                            getLayerRequests() const {
-                        return mLayerRequests;
-                    }
-
-                    void addTypeChange(hwc2_layer_t layerId,
-                            HWC2::Composition type) {
-                        mTypeChanges.insert({layerId, type});
-                    }
-
-                    void clearTypeChanges() { mTypeChanges.clear(); }
-
-                    void addLayerRequest(hwc2_layer_t layerId,
-                            HWC2::LayerRequest request) {
-                        mLayerRequests.insert({layerId, request});
-                    }
-
-                private:
-                    std::unordered_map<hwc2_layer_t, HWC2::Composition>
-                            mTypeChanges;
-                    std::unordered_map<hwc2_layer_t, HWC2::LayerRequest>
-                            mLayerRequests;
-            };
-
-            std::shared_ptr<const Config>
-                    getConfig(hwc2_config_t configId) const;
-
-            void populateColorModes();
-            void initializeActiveConfig();
-
-            // Creates a bi-directional mapping between index in HWC1
-            // prepare/set array and Layer object. Stores mapping in
-            // mHwc1LayerMap and also updates Layer's attribute mHwc1Id.
-            void assignHwc1LayerIds();
-
-            // Called after a response to prepare() has been received:
-            // Ingest composition type changes requested by the device.
-            void updateTypeChanges(const struct hwc_layer_1& hwc1Layer,
-                    const Layer& layer);
-
-            // Called after a response to prepare() has been received:
-            // Ingest layer hint changes requested by the device.
-            void updateLayerRequests(const struct hwc_layer_1& hwc1Layer,
-                    const Layer& layer);
-
-            // Set all fields in HWC1 comm array for layer containing the
-            // HWC_FRAMEBUFFER_TARGET (always the last layer).
-            void prepareFramebufferTarget();
-
-            // Display ID generator.
-            static std::atomic<hwc2_display_t> sNextId;
-            const hwc2_display_t mId;
-
-
-            HWC2On1Adapter& mDevice;
-
-            // The state of this display should only be modified from
-            // SurfaceFlinger's main loop, with the exception of when dump is
-            // called. To prevent a bad state from crashing us during a dump
-            // call, all public calls into Display must acquire this mutex.
-            //
-            // It is recursive because we don't want to deadlock in validate
-            // (or present) when we call HWC2On1Adapter::prepareAllDisplays
-            // (or setAllDisplays), which calls back into Display functions
-            // which require locking.
-            mutable std::recursive_mutex mStateMutex;
-
-            // Allocate RAM able to store all layers and rects used for
-            // communication with HWC1. Place allocated RAM in variable
-            // mHwc1RequestedContents.
-            void allocateRequestedContents();
-
-            // Array of structs exchanged between client and hwc1 device.
-            // Sent to device upon calling prepare().
-            std::unique_ptr<hwc_display_contents_1> mHwc1RequestedContents;
-    private:
-            DeferredFence mRetireFence;
-
-            // Will only be non-null after the Display has been validated and
-            // before it has been presented
-            std::unique_ptr<Changes> mChanges;
-
-            int32_t mHwc1Id;
-
-            std::vector<std::shared_ptr<Config>> mConfigs;
-            std::shared_ptr<const Config> mActiveConfig;
-            std::set<android_color_mode_t> mColorModes;
-            android_color_mode_t mActiveColorMode;
-            std::string mName;
-            HWC2::DisplayType mType;
-            HWC2::PowerMode mPowerMode;
-            HWC2::Vsync mVsyncEnabled;
-
-            // Used to populate HWC1 HWC_FRAMEBUFFER_TARGET layer
-            FencedBuffer mClientTarget;
-
-
-            FencedBuffer mOutputBuffer;
-
-            bool mHasColorTransform;
-
-            // All layers this Display is aware of.
-            std::multiset<std::shared_ptr<Layer>, SortLayersByZ> mLayers;
-
-            // Mapping between layer index in array of hwc_display_contents_1*
-            // passed to HWC1 during validate/set and Layer object.
-            std::unordered_map<size_t, std::shared_ptr<Layer>> mHwc1LayerMap;
-
-            // All communication with HWC1 via prepare/set is done with one
-            // alloc. This pointer is pointing to a pool of hwc_rect_t.
-            size_t mNumAvailableRects;
-            hwc_rect_t* mNextAvailableRect;
-
-            // True if any of the Layers contained in this Display have been
-            // updated with anything other than a buffer since last call to
-            // Display::set()
-            bool mGeometryChanged;
-    };
-
-    // Utility template calling a Display object method directly based on the
-    // hwc2_display_t displayId parameter.
-    template <typename ...Args>
-    static int32_t callDisplayFunction(hwc2_device_t* device,
-            hwc2_display_t displayId, HWC2::Error (Display::*member)(Args...),
-            Args... args) {
-        auto display = getAdapter(device)->getDisplay(displayId);
-        if (!display) {
-            return static_cast<int32_t>(HWC2::Error::BadDisplay);
-        }
-        auto error = ((*display).*member)(std::forward<Args>(args)...);
-        return static_cast<int32_t>(error);
-    }
-
-    template <typename MF, MF memFunc, typename ...Args>
-    static int32_t displayHook(hwc2_device_t* device, hwc2_display_t displayId,
-            Args... args) {
-        return HWC2On1Adapter::callDisplayFunction(device, displayId, memFunc,
-                std::forward<Args>(args)...);
-    }
-
-    static int32_t getDisplayAttributeHook(hwc2_device_t* device,
-            hwc2_display_t display, hwc2_config_t config,
-            int32_t intAttribute, int32_t* outValue) {
-        auto attribute = static_cast<HWC2::Attribute>(intAttribute);
-        return callDisplayFunction(device, display, &Display::getAttribute,
-                config, attribute, outValue);
-    }
-
-    static int32_t setColorTransformHook(hwc2_device_t* device,
-            hwc2_display_t display, const float* /*matrix*/,
-            int32_t /*android_color_transform_t*/ intHint) {
-        // We intentionally throw away the matrix, because if the hint is
-        // anything other than IDENTITY, we have to fall back to client
-        // composition anyway
-        auto hint = static_cast<android_color_transform_t>(intHint);
-        return callDisplayFunction(device, display, &Display::setColorTransform,
-                hint);
-    }
-
-    static int32_t setColorModeHook(hwc2_device_t* device,
-            hwc2_display_t display, int32_t /*android_color_mode_t*/ intMode) {
-        auto mode = static_cast<android_color_mode_t>(intMode);
-        return callDisplayFunction(device, display, &Display::setColorMode,
-                mode);
-    }
-
-    static int32_t setPowerModeHook(hwc2_device_t* device,
-            hwc2_display_t display, int32_t intMode) {
-        auto mode = static_cast<HWC2::PowerMode>(intMode);
-        return callDisplayFunction(device, display, &Display::setPowerMode,
-                mode);
-    }
-
-    static int32_t setVsyncEnabledHook(hwc2_device_t* device,
-            hwc2_display_t display, int32_t intEnabled) {
-        auto enabled = static_cast<HWC2::Vsync>(intEnabled);
-        return callDisplayFunction(device, display, &Display::setVsyncEnabled,
-                enabled);
-    }
-
-    class Layer {
-        public:
-            explicit Layer(Display& display);
-
-            bool operator==(const Layer& other) { return mId == other.mId; }
-            bool operator!=(const Layer& other) { return !(*this == other); }
-
-            hwc2_layer_t getId() const { return mId; }
-            Display& getDisplay() const { return mDisplay; }
-
-            // HWC2 Layer functions
-            HWC2::Error setBuffer(buffer_handle_t buffer, int32_t acquireFence);
-            HWC2::Error setCursorPosition(int32_t x, int32_t y);
-            HWC2::Error setSurfaceDamage(hwc_region_t damage);
-
-            // HWC2 Layer state functions
-            HWC2::Error setBlendMode(HWC2::BlendMode mode);
-            HWC2::Error setColor(hwc_color_t color);
-            HWC2::Error setCompositionType(HWC2::Composition type);
-            HWC2::Error setDataspace(android_dataspace_t dataspace);
-            HWC2::Error setDisplayFrame(hwc_rect_t frame);
-            HWC2::Error setPlaneAlpha(float alpha);
-            HWC2::Error setSidebandStream(const native_handle_t* stream);
-            HWC2::Error setSourceCrop(hwc_frect_t crop);
-            HWC2::Error setTransform(HWC2::Transform transform);
-            HWC2::Error setVisibleRegion(hwc_region_t visible);
-            HWC2::Error setZ(uint32_t z);
-
-            HWC2::Composition getCompositionType() const {
-                return mCompositionType;
-            }
-            uint32_t getZ() const { return mZ; }
-
-            void addReleaseFence(int fenceFd);
-            const sp<MiniFence>& getReleaseFence() const;
-
-            void setHwc1Id(size_t id) { mHwc1Id = id; }
-            size_t getHwc1Id() const { return mHwc1Id; }
-
-            // Write state to HWC1 communication struct.
-            void applyState(struct hwc_layer_1& hwc1Layer);
-
-            std::string dump() const;
-
-            std::size_t getNumVisibleRegions() { return mVisibleRegion.size(); }
-
-            std::size_t getNumSurfaceDamages() { return mSurfaceDamage.size(); }
-
-            // True if a layer cannot be properly rendered by the device due
-            // to usage of SolidColor (a.k.a BackgroundColor in HWC1).
-            bool hasUnsupportedBackgroundColor() {
-                return (mCompositionType == HWC2::Composition::SolidColor &&
-                        !mDisplay.getDevice().supportsBackgroundColor());
-            }
-        private:
-            void applyCommonState(struct hwc_layer_1& hwc1Layer);
-            void applySolidColorState(struct hwc_layer_1& hwc1Layer);
-            void applySidebandState(struct hwc_layer_1& hwc1Layer);
-            void applyBufferState(struct hwc_layer_1& hwc1Layer);
-            void applyCompositionType(struct hwc_layer_1& hwc1Layer);
-
-            static std::atomic<hwc2_layer_t> sNextId;
-            const hwc2_layer_t mId;
-            Display& mDisplay;
-
-            FencedBuffer mBuffer;
-            std::vector<hwc_rect_t> mSurfaceDamage;
-
-            HWC2::BlendMode mBlendMode;
-            hwc_color_t mColor;
-            HWC2::Composition mCompositionType;
-            hwc_rect_t mDisplayFrame;
-            float mPlaneAlpha;
-            const native_handle_t* mSidebandStream;
-            hwc_frect_t mSourceCrop;
-            HWC2::Transform mTransform;
-            std::vector<hwc_rect_t> mVisibleRegion;
-
-            uint32_t mZ;
-
-            DeferredFence mReleaseFence;
-
-            size_t mHwc1Id;
-            bool mHasUnsupportedPlaneAlpha;
-    };
-
-    // Utility tempate calling a Layer object method based on ID parameters:
-    // hwc2_display_t displayId
-    // and
-    // hwc2_layer_t layerId
-    template <typename ...Args>
-    static int32_t callLayerFunction(hwc2_device_t* device,
-            hwc2_display_t displayId, hwc2_layer_t layerId,
-            HWC2::Error (Layer::*member)(Args...), Args... args) {
-        auto result = getAdapter(device)->getLayer(displayId, layerId);
-        auto error = std::get<HWC2::Error>(result);
-        if (error == HWC2::Error::None) {
-            auto layer = std::get<Layer*>(result);
-            error = ((*layer).*member)(std::forward<Args>(args)...);
-        }
-        return static_cast<int32_t>(error);
-    }
-
-    template <typename MF, MF memFunc, typename ...Args>
-    static int32_t layerHook(hwc2_device_t* device, hwc2_display_t displayId,
-            hwc2_layer_t layerId, Args... args) {
-        return HWC2On1Adapter::callLayerFunction(device, displayId, layerId,
-                memFunc, std::forward<Args>(args)...);
-    }
-
-    // Layer state functions
-
-    static int32_t setLayerBlendModeHook(hwc2_device_t* device,
-            hwc2_display_t display, hwc2_layer_t layer, int32_t intMode) {
-        auto mode = static_cast<HWC2::BlendMode>(intMode);
-        return callLayerFunction(device, display, layer,
-                &Layer::setBlendMode, mode);
-    }
-
-    static int32_t setLayerCompositionTypeHook(hwc2_device_t* device,
-            hwc2_display_t display, hwc2_layer_t layer, int32_t intType) {
-        auto type = static_cast<HWC2::Composition>(intType);
-        return callLayerFunction(device, display, layer,
-                &Layer::setCompositionType, type);
-    }
-
-    static int32_t setLayerDataspaceHook(hwc2_device_t* device,
-            hwc2_display_t display, hwc2_layer_t layer, int32_t intDataspace) {
-        auto dataspace = static_cast<android_dataspace_t>(intDataspace);
-        return callLayerFunction(device, display, layer, &Layer::setDataspace,
-                dataspace);
-    }
-
-    static int32_t setLayerTransformHook(hwc2_device_t* device,
-            hwc2_display_t display, hwc2_layer_t layer, int32_t intTransform) {
-        auto transform = static_cast<HWC2::Transform>(intTransform);
-        return callLayerFunction(device, display, layer, &Layer::setTransform,
-                transform);
-    }
-
-    static int32_t setLayerZOrderHook(hwc2_device_t* device,
-            hwc2_display_t display, hwc2_layer_t layer, uint32_t z) {
-        return callDisplayFunction(device, display, &Display::updateLayerZ,
-                layer, z);
-    }
-
-    // Adapter internals
-
-    void populateCapabilities();
-    Display* getDisplay(hwc2_display_t id);
-    std::tuple<Layer*, HWC2::Error> getLayer(hwc2_display_t displayId,
-            hwc2_layer_t layerId);
-    void populatePrimary();
-
-    bool prepareAllDisplays();
-    std::vector<struct hwc_display_contents_1*> mHwc1Contents;
-    HWC2::Error setAllDisplays();
-
-    // Callbacks
-    void hwc1Invalidate();
-    void hwc1Vsync(int hwc1DisplayId, int64_t timestamp);
-    void hwc1Hotplug(int hwc1DisplayId, int connected);
-
-    // These are set in the constructor and before any asynchronous events are
-    // possible
-
-    struct hwc_composer_device_1* const mHwc1Device;
-    const uint8_t mHwc1MinorVersion;
-    bool mHwc1SupportsVirtualDisplays;
-    bool mHwc1SupportsBackgroundColor;
-
-    class Callbacks;
-    const std::unique_ptr<Callbacks> mHwc1Callbacks;
-
-    std::unordered_set<HWC2::Capability> mCapabilities;
-
-    // These are only accessed from the main SurfaceFlinger thread (not from
-    // callbacks or dump
-
-    std::map<hwc2_layer_t, std::shared_ptr<Layer>> mLayers;
-
-    // A HWC1 supports only one virtual display.
-    std::shared_ptr<Display> mHwc1VirtualDisplay;
-
-    // These are potentially accessed from multiple threads, and are protected
-    // by this mutex. This needs to be recursive, since the HWC1 implementation
-    // can call back into the invalidate callback on the same thread that is
-    // calling prepare.
-    std::recursive_timed_mutex mStateMutex;
-
-    struct CallbackInfo {
-        hwc2_callback_data_t data;
-        hwc2_function_pointer_t pointer;
-    };
-    std::unordered_map<HWC2::Callback, CallbackInfo> mCallbacks;
-    bool mHasPendingInvalidate;
-
-    // There is a small gap between the time the HWC1 module is started and
-    // when the callbacks for vsync and hotplugs are registered by the
-    // HWC2on1Adapter. To prevent losing events they are stored in these arrays
-    // and fed to the callback as soon as possible.
-    std::vector<std::pair<int, int64_t>> mPendingVsyncs;
-    std::vector<std::pair<int, int>> mPendingHotplugs;
-
-    // Mapping between HWC1 display id and Display objects.
-    std::map<hwc2_display_t, std::shared_ptr<Display>> mDisplays;
-
-    // Map HWC1 display type (HWC_DISPLAY_PRIMARY, HWC_DISPLAY_EXTERNAL,
-    // HWC_DISPLAY_VIRTUAL) to Display IDs generated by HWC2on1Adapter objects.
-    std::unordered_map<int, hwc2_display_t> mHwc1DisplayMap;
-};
-
-} // namespace android
-
-#endif
diff --git a/libs/hwc2on1adapter/include/hwc2on1adapter/MiniFence.h b/libs/hwc2on1adapter/include/hwc2on1adapter/MiniFence.h
deleted file mode 100644
index 75de764..0000000
--- a/libs/hwc2on1adapter/include/hwc2on1adapter/MiniFence.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef MINIFENCE_H
-#define MINIFENCE_H
-
-#include <utils/RefBase.h>
-
-namespace android {
-
-/* MiniFence is a minimal re-implementation of Fence from libui. It exists to
- * avoid linking the HWC2on1Adapter to libui and satisfy Treble requirements.
- */
-class MiniFence : public LightRefBase<MiniFence> {
-public:
-    static const sp<MiniFence> NO_FENCE;
-
-    // Construct a new MiniFence object with an invalid file descriptor.
-    MiniFence();
-
-    // Construct a new MiniFence object to manage a given fence file descriptor.
-    // When the new MiniFence object is destructed the file descriptor will be
-    // closed.
-    explicit MiniFence(int fenceFd);
-
-    // Not copyable or movable.
-    MiniFence(const MiniFence& rhs) = delete;
-    MiniFence& operator=(const MiniFence& rhs) = delete;
-    MiniFence(MiniFence&& rhs) = delete;
-    MiniFence& operator=(MiniFence&& rhs) = delete;
-
-    // Return a duplicate of the fence file descriptor. The caller is
-    // responsible for closing the returned file descriptor. On error, -1 will
-    // be returned and errno will indicate the problem.
-    int dup() const;
-
-private:
-    // Only allow instantiation using ref counting.
-    friend class LightRefBase<MiniFence>;
-    ~MiniFence();
-
-    int mFenceFd;
-
-};
-}
-#endif //MINIFENCE_H
diff --git a/libs/hwc2onfbadapter/Android.bp b/libs/hwc2onfbadapter/Android.bp
deleted file mode 100644
index 73a41f7..0000000
--- a/libs/hwc2onfbadapter/Android.bp
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2010 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.
-
-cc_library_shared {
-    name: "libhwc2onfbadapter",
-    vendor: true,
-
-    clang: true,
-    cflags: [
-        "-Wall",
-        "-Wextra",
-        "-Werror",
-    ],
-
-    srcs: [
-        "HWC2OnFbAdapter.cpp",
-    ],
-
-    header_libs: ["libhardware_headers"],
-    shared_libs: ["liblog", "libsync"],
-    export_include_dirs: ["include"],
-}
diff --git a/libs/hwc2onfbadapter/HWC2OnFbAdapter.cpp b/libs/hwc2onfbadapter/HWC2OnFbAdapter.cpp
deleted file mode 100644
index 7c9e651..0000000
--- a/libs/hwc2onfbadapter/HWC2OnFbAdapter.cpp
+++ /dev/null
@@ -1,887 +0,0 @@
-/*
- * Copyright 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "HWC2OnFbAdapter"
-
-//#define LOG_NDEBUG 0
-
-#include "hwc2onfbadapter/HWC2OnFbAdapter.h"
-
-#include <algorithm>
-#include <type_traits>
-
-#include <inttypes.h>
-#include <time.h>
-#include <sys/prctl.h>
-#include <unistd.h> // for close
-
-#include <hardware/fb.h>
-#include <log/log.h>
-#include <sync/sync.h>
-
-namespace android {
-
-namespace {
-
-void dumpHook(hwc2_device_t* device, uint32_t* outSize, char* outBuffer) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (outBuffer) {
-        *outSize = adapter.getDebugString().copy(outBuffer, *outSize);
-    } else {
-        adapter.updateDebugString();
-        *outSize = adapter.getDebugString().size();
-    }
-}
-
-int32_t registerCallbackHook(hwc2_device_t* device, int32_t descriptor,
-                             hwc2_callback_data_t callbackData, hwc2_function_pointer_t pointer) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    switch (descriptor) {
-        case HWC2_CALLBACK_HOTPLUG:
-            if (pointer) {
-                reinterpret_cast<HWC2_PFN_HOTPLUG>(pointer)(callbackData, adapter.getDisplayId(),
-                                                            HWC2_CONNECTION_CONNECTED);
-            }
-            break;
-        case HWC2_CALLBACK_REFRESH:
-            break;
-        case HWC2_CALLBACK_VSYNC:
-            adapter.setVsyncCallback(reinterpret_cast<HWC2_PFN_VSYNC>(pointer), callbackData);
-            break;
-        default:
-            return HWC2_ERROR_BAD_PARAMETER;
-    }
-
-    return HWC2_ERROR_NONE;
-}
-
-uint32_t getMaxVirtualDisplayCountHook(hwc2_device_t* /*device*/) {
-    return 0;
-}
-
-int32_t createVirtualDisplayHook(hwc2_device_t* /*device*/, uint32_t /*width*/, uint32_t /*height*/,
-                                 int32_t* /*format*/, hwc2_display_t* /*outDisplay*/) {
-    return HWC2_ERROR_NO_RESOURCES;
-}
-
-int32_t destroyVirtualDisplayHook(hwc2_device_t* /*device*/, hwc2_display_t /*display*/) {
-    return HWC2_ERROR_BAD_DISPLAY;
-}
-
-int32_t setOutputBufferHook(hwc2_device_t* /*device*/, hwc2_display_t /*display*/,
-                            buffer_handle_t /*buffer*/, int32_t /*releaseFence*/) {
-    return HWC2_ERROR_BAD_DISPLAY;
-}
-
-int32_t getDisplayNameHook(hwc2_device_t* device, hwc2_display_t display, uint32_t* outSize,
-                           char* outName) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-
-    const auto& info = adapter.getInfo();
-    if (outName) {
-        *outSize = info.name.copy(outName, *outSize);
-    } else {
-        *outSize = info.name.size();
-    }
-
-    return HWC2_ERROR_NONE;
-}
-
-int32_t getDisplayTypeHook(hwc2_device_t* device, hwc2_display_t display, int32_t* outType) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-
-    *outType = HWC2_DISPLAY_TYPE_PHYSICAL;
-    return HWC2_ERROR_NONE;
-}
-
-int32_t getDozeSupportHook(hwc2_device_t* device, hwc2_display_t display, int32_t* outSupport) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-
-    *outSupport = 0;
-    return HWC2_ERROR_NONE;
-}
-
-int32_t getHdrCapabilitiesHook(hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumTypes,
-                               int32_t* /*outTypes*/, float* /*outMaxLuminance*/,
-                               float* /*outMaxAverageLuminance*/, float* /*outMinLuminance*/) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-
-    *outNumTypes = 0;
-    return HWC2_ERROR_NONE;
-}
-
-int32_t setPowerModeHook(hwc2_device_t* device, hwc2_display_t display, int32_t /*mode*/) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-
-    // pretend that it works
-    return HWC2_ERROR_NONE;
-}
-
-int32_t setVsyncEnabledHook(hwc2_device_t* device, hwc2_display_t display, int32_t enabled) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-
-    adapter.enableVsync(enabled == HWC2_VSYNC_ENABLE);
-    return HWC2_ERROR_NONE;
-}
-
-int32_t getColorModesHook(hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumModes,
-                          int32_t* outModes) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-
-    if (outModes) {
-        if (*outNumModes > 0) {
-            outModes[0] = HAL_COLOR_MODE_NATIVE;
-            *outNumModes = 1;
-        }
-    } else {
-        *outNumModes = 1;
-    }
-
-    return HWC2_ERROR_NONE;
-}
-
-int32_t setColorModeHook(hwc2_device_t* device, hwc2_display_t display, int32_t mode) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-    if (mode != HAL_COLOR_MODE_NATIVE) {
-        return HWC2_ERROR_BAD_PARAMETER;
-    }
-
-    return HWC2_ERROR_NONE;
-}
-
-int32_t setColorTransformHook(hwc2_device_t* device, hwc2_display_t display,
-                              const float* /*matrix*/, int32_t /*hint*/) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-
-    // we always force client composition
-    adapter.setState(HWC2OnFbAdapter::State::MODIFIED);
-    return HWC2_ERROR_NONE;
-}
-
-int32_t getClientTargetSupportHook(hwc2_device_t* device, hwc2_display_t display, uint32_t width,
-                                   uint32_t height, int32_t format, int32_t dataspace) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-    if (dataspace != HAL_DATASPACE_UNKNOWN) {
-        return HWC2_ERROR_UNSUPPORTED;
-    }
-
-    const auto& info = adapter.getInfo();
-    return (info.width == width && info.height == height && info.format == format)
-            ? HWC2_ERROR_NONE
-            : HWC2_ERROR_UNSUPPORTED;
-}
-
-int32_t setClientTargetHook(hwc2_device_t* device, hwc2_display_t display, buffer_handle_t target,
-                            int32_t acquireFence, int32_t dataspace, hwc_region_t /*damage*/) {
-    if (acquireFence >= 0) {
-        sync_wait(acquireFence, -1);
-        close(acquireFence);
-    }
-
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-    if (dataspace != HAL_DATASPACE_UNKNOWN) {
-        return HWC2_ERROR_BAD_PARAMETER;
-    }
-
-    // no state change
-    adapter.setBuffer(target);
-    return HWC2_ERROR_NONE;
-}
-
-int32_t getDisplayConfigsHook(hwc2_device_t* device, hwc2_display_t display,
-                              uint32_t* outNumConfigs, hwc2_config_t* outConfigs) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-
-    if (outConfigs) {
-        if (*outNumConfigs > 0) {
-            outConfigs[0] = adapter.getConfigId();
-            *outNumConfigs = 1;
-        }
-    } else {
-        *outNumConfigs = 1;
-    }
-
-    return HWC2_ERROR_NONE;
-}
-
-int32_t getDisplayAttributeHook(hwc2_device_t* device, hwc2_display_t display, hwc2_config_t config,
-                                int32_t attribute, int32_t* outValue) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-    if (adapter.getConfigId() != config) {
-        return HWC2_ERROR_BAD_CONFIG;
-    }
-
-    const auto& info = adapter.getInfo();
-    switch (attribute) {
-        case HWC2_ATTRIBUTE_WIDTH:
-            *outValue = int32_t(info.width);
-            break;
-        case HWC2_ATTRIBUTE_HEIGHT:
-            *outValue = int32_t(info.height);
-            break;
-        case HWC2_ATTRIBUTE_VSYNC_PERIOD:
-            *outValue = int32_t(info.vsync_period_ns);
-            break;
-        case HWC2_ATTRIBUTE_DPI_X:
-            *outValue = int32_t(info.xdpi_scaled);
-            break;
-        case HWC2_ATTRIBUTE_DPI_Y:
-            *outValue = int32_t(info.ydpi_scaled);
-            break;
-        default:
-            return HWC2_ERROR_BAD_PARAMETER;
-    }
-
-    return HWC2_ERROR_NONE;
-}
-
-int32_t getActiveConfigHook(hwc2_device_t* device, hwc2_display_t display,
-                            hwc2_config_t* outConfig) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-
-    *outConfig = adapter.getConfigId();
-    return HWC2_ERROR_NONE;
-}
-
-int32_t setActiveConfigHook(hwc2_device_t* device, hwc2_display_t display, hwc2_config_t config) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-    if (adapter.getConfigId() != config) {
-        return HWC2_ERROR_BAD_CONFIG;
-    }
-
-    return HWC2_ERROR_NONE;
-}
-
-int32_t validateDisplayHook(hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumTypes,
-                            uint32_t* outNumRequests) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-
-    const auto& dirtyLayers = adapter.getDirtyLayers();
-    *outNumTypes = dirtyLayers.size();
-    *outNumRequests = 0;
-
-    if (*outNumTypes > 0) {
-        adapter.setState(HWC2OnFbAdapter::State::VALIDATED_WITH_CHANGES);
-        return HWC2_ERROR_HAS_CHANGES;
-    } else {
-        adapter.setState(HWC2OnFbAdapter::State::VALIDATED);
-        return HWC2_ERROR_NONE;
-    }
-}
-
-int32_t getChangedCompositionTypesHook(hwc2_device_t* device, hwc2_display_t display,
-                                       uint32_t* outNumElements, hwc2_layer_t* outLayers,
-                                       int32_t* outTypes) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-    if (adapter.getState() == HWC2OnFbAdapter::State::MODIFIED) {
-        return HWC2_ERROR_NOT_VALIDATED;
-    }
-
-    // request client composition for all layers
-    const auto& dirtyLayers = adapter.getDirtyLayers();
-    if (outLayers && outTypes) {
-        *outNumElements = std::min(*outNumElements, uint32_t(dirtyLayers.size()));
-        auto iter = dirtyLayers.cbegin();
-        for (uint32_t i = 0; i < *outNumElements; i++) {
-            outLayers[i] = *iter++;
-            outTypes[i] = HWC2_COMPOSITION_CLIENT;
-        }
-    } else {
-        *outNumElements = dirtyLayers.size();
-    }
-
-    return HWC2_ERROR_NONE;
-}
-
-int32_t getDisplayRequestsHook(hwc2_device_t* device, hwc2_display_t display,
-                               int32_t* outDisplayRequests, uint32_t* outNumElements,
-                               hwc2_layer_t* /*outLayers*/, int32_t* /*outLayerRequests*/) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-    if (adapter.getState() == HWC2OnFbAdapter::State::MODIFIED) {
-        return HWC2_ERROR_NOT_VALIDATED;
-    }
-
-    *outDisplayRequests = 0;
-    *outNumElements = 0;
-    return HWC2_ERROR_NONE;
-}
-
-int32_t acceptDisplayChangesHook(hwc2_device_t* device, hwc2_display_t display) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-    if (adapter.getState() == HWC2OnFbAdapter::State::MODIFIED) {
-        return HWC2_ERROR_NOT_VALIDATED;
-    }
-
-    adapter.clearDirtyLayers();
-    adapter.setState(HWC2OnFbAdapter::State::VALIDATED);
-    return HWC2_ERROR_NONE;
-}
-
-int32_t presentDisplayHook(hwc2_device_t* device, hwc2_display_t display,
-                           int32_t* outPresentFence) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-    if (adapter.getState() != HWC2OnFbAdapter::State::VALIDATED) {
-        return HWC2_ERROR_NOT_VALIDATED;
-    }
-
-    adapter.postBuffer();
-    *outPresentFence = -1;
-
-    return HWC2_ERROR_NONE;
-}
-
-int32_t getReleaseFencesHook(hwc2_device_t* device, hwc2_display_t display,
-                             uint32_t* outNumElements, hwc2_layer_t* /*outLayers*/,
-                             int32_t* /*outFences*/) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-
-    *outNumElements = 0;
-    return HWC2_ERROR_NONE;
-}
-
-int32_t createLayerHook(hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t* outLayer) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-
-    *outLayer = adapter.addLayer();
-    adapter.setState(HWC2OnFbAdapter::State::MODIFIED);
-    return HWC2_ERROR_NONE;
-}
-
-int32_t destroyLayerHook(hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-
-    if (adapter.removeLayer(layer)) {
-        adapter.setState(HWC2OnFbAdapter::State::MODIFIED);
-        return HWC2_ERROR_NONE;
-    } else {
-        return HWC2_ERROR_BAD_LAYER;
-    }
-}
-
-int32_t setCursorPositionHook(hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t /*layer*/,
-                              int32_t /*x*/, int32_t /*y*/) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-
-    // always an error
-    return HWC2_ERROR_BAD_LAYER;
-}
-
-int32_t setLayerBufferHook(hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
-                           buffer_handle_t /*buffer*/, int32_t acquireFence) {
-    if (acquireFence >= 0) {
-        sync_wait(acquireFence, -1);
-        close(acquireFence);
-    }
-
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-    if (!adapter.hasLayer(layer)) {
-        return HWC2_ERROR_BAD_LAYER;
-    }
-
-    // no state change
-    return HWC2_ERROR_NONE;
-}
-
-int32_t setLayerSurfaceDamageHook(hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
-                                  hwc_region_t /*damage*/) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-    if (!adapter.hasLayer(layer)) {
-        return HWC2_ERROR_BAD_LAYER;
-    }
-
-    // no state change
-    return HWC2_ERROR_NONE;
-}
-
-int32_t setLayerCompositionTypeHook(hwc2_device_t* device, hwc2_display_t display,
-                                    hwc2_layer_t layer, int32_t type) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-    if (!adapter.markLayerDirty(layer, type != HWC2_COMPOSITION_CLIENT)) {
-        return HWC2_ERROR_BAD_LAYER;
-    }
-
-    adapter.setState(HWC2OnFbAdapter::State::MODIFIED);
-    return HWC2_ERROR_NONE;
-}
-
-template <typename... Args>
-int32_t setLayerStateHook(hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
-                          Args... /*args*/) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    if (adapter.getDisplayId() != display) {
-        return HWC2_ERROR_BAD_DISPLAY;
-    }
-    if (!adapter.hasLayer(layer)) {
-        return HWC2_ERROR_BAD_LAYER;
-    }
-
-    adapter.setState(HWC2OnFbAdapter::State::MODIFIED);
-    return HWC2_ERROR_NONE;
-}
-
-template <typename PFN, typename T>
-static hwc2_function_pointer_t asFP(T function) {
-    static_assert(std::is_same<PFN, T>::value, "Incompatible function pointer");
-    return reinterpret_cast<hwc2_function_pointer_t>(function);
-}
-
-hwc2_function_pointer_t getFunctionHook(hwc2_device_t* /*device*/, int32_t descriptor) {
-    switch (descriptor) {
-        // global functions
-        case HWC2_FUNCTION_DUMP:
-            return asFP<HWC2_PFN_DUMP>(dumpHook);
-        case HWC2_FUNCTION_REGISTER_CALLBACK:
-            return asFP<HWC2_PFN_REGISTER_CALLBACK>(registerCallbackHook);
-
-        // virtual display functions
-        case HWC2_FUNCTION_GET_MAX_VIRTUAL_DISPLAY_COUNT:
-            return asFP<HWC2_PFN_GET_MAX_VIRTUAL_DISPLAY_COUNT>(getMaxVirtualDisplayCountHook);
-        case HWC2_FUNCTION_CREATE_VIRTUAL_DISPLAY:
-            return asFP<HWC2_PFN_CREATE_VIRTUAL_DISPLAY>(createVirtualDisplayHook);
-        case HWC2_FUNCTION_DESTROY_VIRTUAL_DISPLAY:
-            return asFP<HWC2_PFN_DESTROY_VIRTUAL_DISPLAY>(destroyVirtualDisplayHook);
-        case HWC2_FUNCTION_SET_OUTPUT_BUFFER:
-            return asFP<HWC2_PFN_SET_OUTPUT_BUFFER>(setOutputBufferHook);
-
-        // display functions
-        case HWC2_FUNCTION_GET_DISPLAY_NAME:
-            return asFP<HWC2_PFN_GET_DISPLAY_NAME>(getDisplayNameHook);
-        case HWC2_FUNCTION_GET_DISPLAY_TYPE:
-            return asFP<HWC2_PFN_GET_DISPLAY_TYPE>(getDisplayTypeHook);
-        case HWC2_FUNCTION_GET_DOZE_SUPPORT:
-            return asFP<HWC2_PFN_GET_DOZE_SUPPORT>(getDozeSupportHook);
-        case HWC2_FUNCTION_GET_HDR_CAPABILITIES:
-            return asFP<HWC2_PFN_GET_HDR_CAPABILITIES>(getHdrCapabilitiesHook);
-        case HWC2_FUNCTION_SET_POWER_MODE:
-            return asFP<HWC2_PFN_SET_POWER_MODE>(setPowerModeHook);
-        case HWC2_FUNCTION_SET_VSYNC_ENABLED:
-            return asFP<HWC2_PFN_SET_VSYNC_ENABLED>(setVsyncEnabledHook);
-        case HWC2_FUNCTION_GET_COLOR_MODES:
-            return asFP<HWC2_PFN_GET_COLOR_MODES>(getColorModesHook);
-        case HWC2_FUNCTION_SET_COLOR_MODE:
-            return asFP<HWC2_PFN_SET_COLOR_MODE>(setColorModeHook);
-        case HWC2_FUNCTION_SET_COLOR_TRANSFORM:
-            return asFP<HWC2_PFN_SET_COLOR_TRANSFORM>(setColorTransformHook);
-        case HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT:
-            return asFP<HWC2_PFN_GET_CLIENT_TARGET_SUPPORT>(getClientTargetSupportHook);
-        case HWC2_FUNCTION_SET_CLIENT_TARGET:
-            return asFP<HWC2_PFN_SET_CLIENT_TARGET>(setClientTargetHook);
-
-        // config functions
-        case HWC2_FUNCTION_GET_DISPLAY_CONFIGS:
-            return asFP<HWC2_PFN_GET_DISPLAY_CONFIGS>(getDisplayConfigsHook);
-        case HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE:
-            return asFP<HWC2_PFN_GET_DISPLAY_ATTRIBUTE>(getDisplayAttributeHook);
-        case HWC2_FUNCTION_GET_ACTIVE_CONFIG:
-            return asFP<HWC2_PFN_GET_ACTIVE_CONFIG>(getActiveConfigHook);
-        case HWC2_FUNCTION_SET_ACTIVE_CONFIG:
-            return asFP<HWC2_PFN_SET_ACTIVE_CONFIG>(setActiveConfigHook);
-
-        // validate/present functions
-        case HWC2_FUNCTION_VALIDATE_DISPLAY:
-            return asFP<HWC2_PFN_VALIDATE_DISPLAY>(validateDisplayHook);
-        case HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES:
-            return asFP<HWC2_PFN_GET_CHANGED_COMPOSITION_TYPES>(getChangedCompositionTypesHook);
-        case HWC2_FUNCTION_GET_DISPLAY_REQUESTS:
-            return asFP<HWC2_PFN_GET_DISPLAY_REQUESTS>(getDisplayRequestsHook);
-        case HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES:
-            return asFP<HWC2_PFN_ACCEPT_DISPLAY_CHANGES>(acceptDisplayChangesHook);
-        case HWC2_FUNCTION_PRESENT_DISPLAY:
-            return asFP<HWC2_PFN_PRESENT_DISPLAY>(presentDisplayHook);
-        case HWC2_FUNCTION_GET_RELEASE_FENCES:
-            return asFP<HWC2_PFN_GET_RELEASE_FENCES>(getReleaseFencesHook);
-
-        // layer create/destroy
-        case HWC2_FUNCTION_CREATE_LAYER:
-            return asFP<HWC2_PFN_CREATE_LAYER>(createLayerHook);
-        case HWC2_FUNCTION_DESTROY_LAYER:
-            return asFP<HWC2_PFN_DESTROY_LAYER>(destroyLayerHook);
-
-        // layer functions; validateDisplay not required
-        case HWC2_FUNCTION_SET_CURSOR_POSITION:
-            return asFP<HWC2_PFN_SET_CURSOR_POSITION>(setCursorPositionHook);
-        case HWC2_FUNCTION_SET_LAYER_BUFFER:
-            return asFP<HWC2_PFN_SET_LAYER_BUFFER>(setLayerBufferHook);
-        case HWC2_FUNCTION_SET_LAYER_SURFACE_DAMAGE:
-            return asFP<HWC2_PFN_SET_LAYER_SURFACE_DAMAGE>(setLayerSurfaceDamageHook);
-
-        // layer state functions; validateDisplay required
-        case HWC2_FUNCTION_SET_LAYER_COMPOSITION_TYPE:
-            return asFP<HWC2_PFN_SET_LAYER_COMPOSITION_TYPE>(setLayerCompositionTypeHook);
-        case HWC2_FUNCTION_SET_LAYER_BLEND_MODE:
-            return asFP<HWC2_PFN_SET_LAYER_BLEND_MODE>(setLayerStateHook<int32_t>);
-        case HWC2_FUNCTION_SET_LAYER_COLOR:
-            return asFP<HWC2_PFN_SET_LAYER_COLOR>(setLayerStateHook<hwc_color_t>);
-        case HWC2_FUNCTION_SET_LAYER_DATASPACE:
-            return asFP<HWC2_PFN_SET_LAYER_DATASPACE>(setLayerStateHook<int32_t>);
-        case HWC2_FUNCTION_SET_LAYER_DISPLAY_FRAME:
-            return asFP<HWC2_PFN_SET_LAYER_DISPLAY_FRAME>(setLayerStateHook<hwc_rect_t>);
-        case HWC2_FUNCTION_SET_LAYER_PLANE_ALPHA:
-            return asFP<HWC2_PFN_SET_LAYER_PLANE_ALPHA>(setLayerStateHook<float>);
-        case HWC2_FUNCTION_SET_LAYER_SIDEBAND_STREAM:
-            return asFP<HWC2_PFN_SET_LAYER_SIDEBAND_STREAM>(setLayerStateHook<buffer_handle_t>);
-        case HWC2_FUNCTION_SET_LAYER_SOURCE_CROP:
-            return asFP<HWC2_PFN_SET_LAYER_SOURCE_CROP>(setLayerStateHook<hwc_frect_t>);
-        case HWC2_FUNCTION_SET_LAYER_TRANSFORM:
-            return asFP<HWC2_PFN_SET_LAYER_TRANSFORM>(setLayerStateHook<int32_t>);
-        case HWC2_FUNCTION_SET_LAYER_VISIBLE_REGION:
-            return asFP<HWC2_PFN_SET_LAYER_VISIBLE_REGION>(setLayerStateHook<hwc_region_t>);
-        case HWC2_FUNCTION_SET_LAYER_Z_ORDER:
-            return asFP<HWC2_PFN_SET_LAYER_Z_ORDER>(setLayerStateHook<uint32_t>);
-
-        default:
-            ALOGE("unknown function descriptor %d", descriptor);
-            return nullptr;
-    }
-}
-
-void getCapabilitiesHook(hwc2_device_t* /*device*/, uint32_t* outCount,
-                         int32_t* /*outCapabilities*/) {
-    *outCount = 0;
-}
-
-int closeHook(hw_device_t* device) {
-    auto& adapter = HWC2OnFbAdapter::cast(device);
-    adapter.close();
-    return 0;
-}
-
-} // anonymous namespace
-
-HWC2OnFbAdapter::HWC2OnFbAdapter(framebuffer_device_t* fbDevice)
-      : hwc2_device_t(), mFbDevice(fbDevice) {
-    common.close = closeHook;
-    hwc2_device::getCapabilities = getCapabilitiesHook;
-    hwc2_device::getFunction = getFunctionHook;
-
-    mFbInfo.name = "fbdev";
-    mFbInfo.width = mFbDevice->width;
-    mFbInfo.height = mFbDevice->height;
-    mFbInfo.format = mFbDevice->format;
-    mFbInfo.vsync_period_ns = int(1e9 / mFbDevice->fps);
-    mFbInfo.xdpi_scaled = int(mFbDevice->xdpi * 1000.0f);
-    mFbInfo.ydpi_scaled = int(mFbDevice->ydpi * 1000.0f);
-
-    mVsyncThread.start(0, mFbInfo.vsync_period_ns);
-}
-
-HWC2OnFbAdapter& HWC2OnFbAdapter::cast(hw_device_t* device) {
-    return *reinterpret_cast<HWC2OnFbAdapter*>(device);
-}
-
-HWC2OnFbAdapter& HWC2OnFbAdapter::cast(hwc2_device_t* device) {
-    return *reinterpret_cast<HWC2OnFbAdapter*>(device);
-}
-
-hwc2_display_t HWC2OnFbAdapter::getDisplayId() {
-    return 0;
-}
-
-hwc2_config_t HWC2OnFbAdapter::getConfigId() {
-    return 0;
-}
-
-void HWC2OnFbAdapter::close() {
-    mVsyncThread.stop();
-    framebuffer_close(mFbDevice);
-}
-
-const HWC2OnFbAdapter::Info& HWC2OnFbAdapter::getInfo() const {
-    return mFbInfo;
-}
-
-void HWC2OnFbAdapter::updateDebugString() {
-    if (mFbDevice->common.version >= 1 && mFbDevice->dump) {
-        char buffer[4096];
-        mFbDevice->dump(mFbDevice, buffer, sizeof(buffer));
-        buffer[sizeof(buffer) - 1] = '\0';
-
-        mDebugString = buffer;
-    }
-}
-
-const std::string& HWC2OnFbAdapter::getDebugString() const {
-    return mDebugString;
-}
-
-void HWC2OnFbAdapter::setState(State state) {
-    mState = state;
-}
-
-HWC2OnFbAdapter::State HWC2OnFbAdapter::getState() const {
-    return mState;
-}
-
-hwc2_layer_t HWC2OnFbAdapter::addLayer() {
-    hwc2_layer_t id = ++mNextLayerId;
-
-    mLayers.insert(id);
-    mDirtyLayers.insert(id);
-
-    return id;
-}
-
-bool HWC2OnFbAdapter::removeLayer(hwc2_layer_t layer) {
-    mDirtyLayers.erase(layer);
-    return mLayers.erase(layer);
-}
-
-bool HWC2OnFbAdapter::hasLayer(hwc2_layer_t layer) const {
-    return mLayers.count(layer) > 0;
-}
-
-bool HWC2OnFbAdapter::markLayerDirty(hwc2_layer_t layer, bool dirty) {
-    if (mLayers.count(layer) == 0) {
-        return false;
-    }
-
-    if (dirty) {
-        mDirtyLayers.insert(layer);
-    } else {
-        mDirtyLayers.erase(layer);
-    }
-
-    return true;
-}
-
-const std::unordered_set<hwc2_layer_t>& HWC2OnFbAdapter::getDirtyLayers() const {
-    return mDirtyLayers;
-}
-
-void HWC2OnFbAdapter::clearDirtyLayers() {
-    mDirtyLayers.clear();
-}
-
-/*
- * For each frame, SurfaceFlinger
- *
- *  - peforms GLES composition
- *  - calls eglSwapBuffers
- *  - calls setClientTarget, which maps to setBuffer below
- *  - calls presentDisplay, which maps to postBuffer below
- *
- * setBuffer should be a good place to call compositionComplete.
- *
- * As for post, it
- *
- *  - schedules the buffer for presentation on the next vsync
- *  - locks the buffer and blocks all other users trying to lock it
- *
- * It does not give us a way to return a present fence, and we need to live
- * with that.  The implication is that, when we are double-buffered,
- * SurfaceFlinger assumes the front buffer is available for rendering again
- * immediately after the back buffer is posted.  The locking semantics
- * hopefully are strong enough that the rendering will be blocked.
- */
-void HWC2OnFbAdapter::setBuffer(buffer_handle_t buffer) {
-    if (mFbDevice->compositionComplete) {
-        mFbDevice->compositionComplete(mFbDevice);
-    }
-    mBuffer = buffer;
-}
-
-bool HWC2OnFbAdapter::postBuffer() {
-    int error = 0;
-    if (mBuffer) {
-        error = mFbDevice->post(mFbDevice, mBuffer);
-    }
-
-    return error == 0;
-}
-
-void HWC2OnFbAdapter::setVsyncCallback(HWC2_PFN_VSYNC callback, hwc2_callback_data_t data) {
-    mVsyncThread.setCallback(callback, data);
-}
-
-void HWC2OnFbAdapter::enableVsync(bool enable) {
-    mVsyncThread.enableCallback(enable);
-}
-
-int64_t HWC2OnFbAdapter::VsyncThread::now() {
-    struct timespec ts;
-    clock_gettime(CLOCK_MONOTONIC, &ts);
-
-    return int64_t(ts.tv_sec) * 1'000'000'000 + ts.tv_nsec;
-}
-
-bool HWC2OnFbAdapter::VsyncThread::sleepUntil(int64_t t) {
-    struct timespec ts;
-    ts.tv_sec = t / 1'000'000'000;
-    ts.tv_nsec = t % 1'000'000'000;
-
-    while (true) {
-        int error = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, nullptr);
-        if (error) {
-            if (error == EINTR) {
-                continue;
-            }
-            return false;
-        } else {
-            return true;
-        }
-    }
-}
-
-void HWC2OnFbAdapter::VsyncThread::start(int64_t firstVsync, int64_t period) {
-    mNextVsync = firstVsync;
-    mPeriod = period;
-    mStarted = true;
-    mThread = std::thread(&VsyncThread::vsyncLoop, this);
-}
-
-void HWC2OnFbAdapter::VsyncThread::stop() {
-    {
-        std::lock_guard<std::mutex> lock(mMutex);
-        mStarted = false;
-    }
-    mCondition.notify_all();
-    mThread.join();
-}
-
-void HWC2OnFbAdapter::VsyncThread::setCallback(HWC2_PFN_VSYNC callback, hwc2_callback_data_t data) {
-    std::lock_guard<std::mutex> lock(mMutex);
-    mCallback = callback;
-    mCallbackData = data;
-}
-
-void HWC2OnFbAdapter::VsyncThread::enableCallback(bool enable) {
-    {
-        std::lock_guard<std::mutex> lock(mMutex);
-        mCallbackEnabled = enable;
-    }
-    mCondition.notify_all();
-}
-
-void HWC2OnFbAdapter::VsyncThread::vsyncLoop() {
-    prctl(PR_SET_NAME, "VsyncThread", 0, 0, 0);
-
-    std::unique_lock<std::mutex> lock(mMutex);
-    if (!mStarted) {
-        return;
-    }
-
-    while (true) {
-        if (!mCallbackEnabled) {
-            mCondition.wait(lock, [this] { return mCallbackEnabled || !mStarted; });
-            if (!mStarted) {
-                break;
-            }
-        }
-
-        lock.unlock();
-
-        // adjust mNextVsync if necessary
-        int64_t t = now();
-        if (mNextVsync < t) {
-            int64_t n = (t - mNextVsync + mPeriod - 1) / mPeriod;
-            mNextVsync += mPeriod * n;
-        }
-        bool fire = sleepUntil(mNextVsync);
-
-        lock.lock();
-
-        if (fire) {
-            ALOGV("VsyncThread(%" PRId64 ")", mNextVsync);
-            if (mCallback) {
-                mCallback(mCallbackData, getDisplayId(), mNextVsync);
-            }
-            mNextVsync += mPeriod;
-        }
-    }
-}
-
-} // namespace android
diff --git a/libs/hwc2onfbadapter/include/hwc2onfbadapter/HWC2OnFbAdapter.h b/libs/hwc2onfbadapter/include/hwc2onfbadapter/HWC2OnFbAdapter.h
deleted file mode 100644
index d6272fd..0000000
--- a/libs/hwc2onfbadapter/include/hwc2onfbadapter/HWC2OnFbAdapter.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_SF_HWC2_ON_FB_ADAPTER_H
-#define ANDROID_SF_HWC2_ON_FB_ADAPTER_H
-
-#include <condition_variable>
-#include <mutex>
-#include <string>
-#include <thread>
-#include <unordered_set>
-
-#include <hardware/hwcomposer2.h>
-
-struct framebuffer_device_t;
-
-namespace android {
-
-class HWC2OnFbAdapter : public hwc2_device_t {
-public:
-    HWC2OnFbAdapter(framebuffer_device_t* fbDevice);
-
-    static HWC2OnFbAdapter& cast(hw_device_t* device);
-    static HWC2OnFbAdapter& cast(hwc2_device_t* device);
-
-    static hwc2_display_t getDisplayId();
-    static hwc2_config_t getConfigId();
-
-    void close();
-
-    struct Info {
-        std::string name;
-        uint32_t width;
-        uint32_t height;
-        int format;
-        int vsync_period_ns;
-        int xdpi_scaled;
-        int ydpi_scaled;
-    };
-    const Info& getInfo() const;
-
-    void updateDebugString();
-    const std::string& getDebugString() const;
-
-    enum class State {
-        MODIFIED,
-        VALIDATED_WITH_CHANGES,
-        VALIDATED,
-    };
-    void setState(State state);
-    State getState() const;
-
-    hwc2_layer_t addLayer();
-    bool removeLayer(hwc2_layer_t layer);
-    bool hasLayer(hwc2_layer_t layer) const;
-    bool markLayerDirty(hwc2_layer_t layer, bool dirty);
-    const std::unordered_set<hwc2_layer_t>& getDirtyLayers() const;
-    void clearDirtyLayers();
-
-    void setBuffer(buffer_handle_t buffer);
-    bool postBuffer();
-
-    void setVsyncCallback(HWC2_PFN_VSYNC callback, hwc2_callback_data_t data);
-    void enableVsync(bool enable);
-
-private:
-    framebuffer_device_t* mFbDevice{nullptr};
-    Info mFbInfo{};
-
-    std::string mDebugString;
-
-    State mState{State::MODIFIED};
-
-    uint64_t mNextLayerId{0};
-    std::unordered_set<hwc2_layer_t> mLayers;
-    std::unordered_set<hwc2_layer_t> mDirtyLayers;
-
-    buffer_handle_t mBuffer{nullptr};
-
-    class VsyncThread {
-    public:
-        static int64_t now();
-        static bool sleepUntil(int64_t t);
-
-        void start(int64_t first, int64_t period);
-        void stop();
-        void setCallback(HWC2_PFN_VSYNC callback, hwc2_callback_data_t data);
-        void enableCallback(bool enable);
-
-    private:
-        void vsyncLoop();
-        bool waitUntilNextVsync();
-
-        std::thread mThread;
-        int64_t mNextVsync{0};
-        int64_t mPeriod{0};
-
-        std::mutex mMutex;
-        std::condition_variable mCondition;
-        bool mStarted{false};
-        HWC2_PFN_VSYNC mCallback{nullptr};
-        hwc2_callback_data_t mCallbackData{nullptr};
-        bool mCallbackEnabled{false};
-    };
-    VsyncThread mVsyncThread;
-};
-
-} // namespace android
-
-#endif // ANDROID_SF_HWC2_ON_FB_ADAPTER_H
diff --git a/libs/input/InputTransport.cpp b/libs/input/InputTransport.cpp
index 5fe8d8b..aa0bf17 100644
--- a/libs/input/InputTransport.cpp
+++ b/libs/input/InputTransport.cpp
@@ -614,10 +614,7 @@
         if (index >= 0) {
             TouchState& touchState = mTouchStates.editItemAt(index);
             touchState.addHistory(msg);
-            bool messageRewritten = rewriteMessage(touchState, msg);
-            if (!messageRewritten) {
-                touchState.lastResample.idBits.clear();
-            }
+            rewriteMessage(touchState, msg);
         }
         break;
     }
@@ -645,7 +642,7 @@
     case AMOTION_EVENT_ACTION_SCROLL: {
         ssize_t index = findTouchState(deviceId, source);
         if (index >= 0) {
-            const TouchState& touchState = mTouchStates.itemAt(index);
+            TouchState& touchState = mTouchStates.editItemAt(index);
             rewriteMessage(touchState, msg);
         }
         break;
@@ -655,7 +652,7 @@
     case AMOTION_EVENT_ACTION_CANCEL: {
         ssize_t index = findTouchState(deviceId, source);
         if (index >= 0) {
-            const TouchState& touchState = mTouchStates.itemAt(index);
+            TouchState& touchState = mTouchStates.editItemAt(index);
             rewriteMessage(touchState, msg);
             mTouchStates.removeAt(index);
         }
@@ -664,28 +661,38 @@
     }
 }
 
-bool InputConsumer::rewriteMessage(const TouchState& state, InputMessage& msg) {
-    bool messageRewritten = false;
+/**
+ * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
+ *
+ * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
+ * is in the past relative to msg and the past two events do not contain identical coordinates),
+ * then invalidate the lastResample data for that pointer.
+ * If the two past events have identical coordinates, then lastResample data for that pointer will
+ * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
+ * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
+ * not equal to x0 is received.
+ */
+void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
     nsecs_t eventTime = msg.body.motion.eventTime;
     for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
         uint32_t id = msg.body.motion.pointers[i].properties.id;
         if (state.lastResample.idBits.hasBit(id)) {
-            PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
-            const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
             if (eventTime < state.lastResample.eventTime ||
                     state.recentCoordinatesAreIdentical(id)) {
-                msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
-                msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
+                PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
+                const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
 #if DEBUG_RESAMPLING
                 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
                         resampleCoords.getX(), resampleCoords.getY(),
                         msgCoords.getX(), msgCoords.getY());
 #endif
-                messageRewritten = true;
+                msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
+                msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
+            } else {
+                state.lastResample.idBits.clearBit(id);
             }
         }
     }
-    return messageRewritten;
 }
 
 void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
@@ -713,7 +720,6 @@
     }
 
     // Ensure that the current sample has all of the pointers that need to be reported.
-    // Also ensure that the past two "real" touch events do not contain duplicate coordinates
     const History* current = touchState.getHistory(0);
     size_t pointerCount = event->getPointerCount();
     for (size_t i = 0; i < pointerCount; i++) {
@@ -724,12 +730,6 @@
 #endif
             return;
         }
-        if (touchState.recentCoordinatesAreIdentical(id)) {
-#if DEBUG_RESAMPLING
-            ALOGD("Not resampled, past two historical events have duplicate coordinates");
-#endif
-            return;
-        }
     }
 
     // Find the data to use for resampling.
@@ -783,18 +783,32 @@
     }
 
     // Resample touch coordinates.
+    History oldLastResample;
+    oldLastResample.initializeFrom(touchState.lastResample);
     touchState.lastResample.eventTime = sampleTime;
     touchState.lastResample.idBits.clear();
     for (size_t i = 0; i < pointerCount; i++) {
         uint32_t id = event->getPointerId(i);
         touchState.lastResample.idToIndex[id] = i;
         touchState.lastResample.idBits.markBit(id);
+        if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
+            // We maintain the previously resampled value for this pointer (stored in
+            // oldLastResample) when the coordinates for this pointer haven't changed since then.
+            // This way we don't introduce artificial jitter when pointers haven't actually moved.
+
+            // We know here that the coordinates for the pointer haven't changed because we
+            // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
+            // lastResample in place becasue the mapping from pointer ID to index may have changed.
+            touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
+            continue;
+        }
+
         PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
         const PointerCoords& currentCoords = current->getPointerById(id);
+        resampledCoords.copyFrom(currentCoords);
         if (other->idBits.hasBit(id)
                 && shouldResampleTool(event->getToolType(i))) {
             const PointerCoords& otherCoords = other->getPointerById(id);
-            resampledCoords.copyFrom(currentCoords);
             resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
                     lerp(currentCoords.getX(), otherCoords.getX(), alpha));
             resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
@@ -808,7 +822,6 @@
                     alpha);
 #endif
         } else {
-            resampledCoords.copyFrom(currentCoords);
 #if DEBUG_RESAMPLING
             ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
                     id, resampledCoords.getX(), resampledCoords.getY(),
diff --git a/libs/input/KeyCharacterMap.cpp b/libs/input/KeyCharacterMap.cpp
index 0627ca6..cba1111 100644
--- a/libs/input/KeyCharacterMap.cpp
+++ b/libs/input/KeyCharacterMap.cpp
@@ -824,6 +824,9 @@
     } else if (typeToken == "FULL") {
         type = KEYBOARD_TYPE_FULL;
     } else if (typeToken == "SPECIAL_FUNCTION") {
+        ALOGW("The SPECIAL_FUNCTION type is now declared in the device's IDC file, please set "
+                "the property 'keyboard.specialFunction' to '1' there instead.");
+        // TODO: return BAD_VALUE here in Q
         type = KEYBOARD_TYPE_SPECIAL_FUNCTION;
     } else if (typeToken == "OVERLAY") {
         type = KEYBOARD_TYPE_OVERLAY;
diff --git a/libs/input/Keyboard.cpp b/libs/input/Keyboard.cpp
index 07f2289..11842ee 100644
--- a/libs/input/Keyboard.cpp
+++ b/libs/input/Keyboard.cpp
@@ -148,9 +148,19 @@
 
 // --- Global functions ---
 
+bool isKeyboardSpecialFunction(const PropertyMap* config) {
+    if (config == nullptr) {
+        return false;
+    }
+    bool isSpecialFunction = false;
+    config->tryGetProperty(String8("keyboard.specialFunction"), isSpecialFunction);
+    return isSpecialFunction;
+}
+
 bool isEligibleBuiltInKeyboard(const InputDeviceIdentifier& deviceIdentifier,
         const PropertyMap* deviceConfiguration, const KeyMap* keyMap) {
-    if (!keyMap->haveKeyCharacterMap()
+    // TODO: remove the third OR statement (SPECIAL_FUNCTION) in Q
+    if (!keyMap->haveKeyCharacterMap() || isKeyboardSpecialFunction(deviceConfiguration)
             || keyMap->keyCharacterMap->getKeyboardType()
                     == KeyCharacterMap::KEYBOARD_TYPE_SPECIAL_FUNCTION) {
         return false;
diff --git a/libs/nativewindow/include/system/window.h b/libs/nativewindow/include/system/window.h
index 5fa1212..197f73f 100644
--- a/libs/nativewindow/include/system/window.h
+++ b/libs/nativewindow/include/system/window.h
@@ -184,6 +184,11 @@
      * Returns data space for the buffers.
      */
     NATIVE_WINDOW_DATASPACE = 20,
+
+    /*
+     * Returns maxBufferCount set by BufferQueueConsumer
+     */
+    NATIVE_WINDOW_MAX_BUFFER_COUNT = 21,
 };
 
 /* Valid operations for the (*perform)() hook.
diff --git a/libs/vr/libbufferhub/buffer_hub-test.cpp b/libs/vr/libbufferhub/buffer_hub-test.cpp
index 471ec7b..b7a6099 100644
--- a/libs/vr/libbufferhub/buffer_hub-test.cpp
+++ b/libs/vr/libbufferhub/buffer_hub-test.cpp
@@ -599,74 +599,6 @@
   EXPECT_NE(0, p->Post(LocalHandle(), sequence));
 }
 
-TEST_F(LibBufferHubTest, TestPersistentBufferPersistence) {
-  auto p = BufferProducer::Create("TestPersistentBuffer", -1, -1, kWidth,
-                                  kHeight, kFormat, kUsage);
-  ASSERT_NE(nullptr, p);
-
-  // Record the original buffer id for later comparison.
-  const int buffer_id = p->id();
-
-  auto c = BufferConsumer::Import(p->CreateConsumer());
-  ASSERT_NE(nullptr, c);
-
-  EXPECT_EQ(0, p->Post<void>(LocalHandle()));
-
-  // Close the connection to the producer. This should not affect the consumer.
-  p = nullptr;
-
-  LocalHandle fence;
-  EXPECT_EQ(0, c->Acquire(&fence));
-  EXPECT_EQ(0, c->Release(LocalHandle()));
-
-  // Attempt to reconnect to the persistent buffer.
-  p = BufferProducer::Create("TestPersistentBuffer");
-  ASSERT_NE(nullptr, p);
-  EXPECT_EQ(buffer_id, p->id());
-  EXPECT_EQ(0, p->Gain(&fence));
-}
-
-TEST_F(LibBufferHubTest, TestPersistentBufferMismatchParams) {
-  auto p = BufferProducer::Create("TestPersistentBuffer", -1, -1, kWidth,
-                                  kHeight, kFormat, kUsage);
-  ASSERT_NE(nullptr, p);
-
-  // Close the connection to the producer.
-  p = nullptr;
-
-  // Mismatch the params.
-  p = BufferProducer::Create("TestPersistentBuffer", -1, -1, kWidth * 2,
-                             kHeight, kFormat, kUsage);
-  ASSERT_EQ(nullptr, p);
-}
-
-TEST_F(LibBufferHubTest, TestRemovePersistentBuffer) {
-  auto p = BufferProducer::Create("TestPersistentBuffer", -1, -1, kWidth,
-                                  kHeight, kFormat, kUsage);
-  ASSERT_NE(nullptr, p);
-
-  LocalHandle fence;
-  auto c = BufferConsumer::Import(p->CreateConsumer());
-  ASSERT_NE(nullptr, c);
-  EXPECT_EQ(0, p->Post<void>(LocalHandle()));
-  EXPECT_EQ(0, c->Acquire(&fence));
-  EXPECT_EQ(0, c->Release(LocalHandle()));
-  EXPECT_LT(0, RETRY_EINTR(p->Poll(kPollTimeoutMs)));
-
-  // Test that removing persistence and closing the producer orphans the
-  // consumer.
-  EXPECT_EQ(0, p->Gain(&fence));
-  EXPECT_EQ(0, p->Post<void>(LocalHandle()));
-  EXPECT_EQ(0, p->RemovePersistence());
-  p = nullptr;
-
-  // Orphaned consumer can acquire the posted buffer one more time in
-  // asynchronous manner. But synchronous call will fail.
-  DvrNativeBufferMetadata meta;
-  EXPECT_EQ(0, c->AcquireAsync(&meta, &fence));
-  EXPECT_EQ(-EPIPE, c->Release(LocalHandle()));
-}
-
 namespace {
 
 int PollFd(int fd, int timeout_ms) {
diff --git a/libs/vr/libbufferhub/buffer_hub_client.cpp b/libs/vr/libbufferhub/buffer_hub_client.cpp
index 97341b1..8fe9dfb 100644
--- a/libs/vr/libbufferhub/buffer_hub_client.cpp
+++ b/libs/vr/libbufferhub/buffer_hub_client.cpp
@@ -431,50 +431,6 @@
   }
 }
 
-BufferProducer::BufferProducer(const std::string& name, int user_id,
-                               int group_id, uint32_t width, uint32_t height,
-                               uint32_t format, uint32_t usage,
-                               size_t user_metadata_size)
-    : BufferProducer(name, user_id, group_id, width, height, format, usage,
-                     usage, user_metadata_size) {}
-
-BufferProducer::BufferProducer(const std::string& name, int user_id,
-                               int group_id, uint32_t width, uint32_t height,
-                               uint32_t format, uint64_t producer_usage,
-                               uint64_t consumer_usage,
-                               size_t user_metadata_size)
-    : BASE(BufferHubRPC::kClientPath) {
-  ATRACE_NAME("BufferProducer::BufferProducer");
-  ALOGD_IF(TRACE,
-           "BufferProducer::BufferProducer: fd=%d name=%s user_id=%d "
-           "group_id=%d width=%u height=%u format=%u producer_usage=%" PRIx64
-           " consumer_usage=%" PRIx64 " user_metadata_size=%zu",
-           event_fd(), name.c_str(), user_id, group_id, width, height, format,
-           producer_usage, consumer_usage, user_metadata_size);
-
-  // (b/37881101) Deprecate producer/consumer usage
-  auto status = InvokeRemoteMethod<BufferHubRPC::CreatePersistentBuffer>(
-      name, user_id, group_id, width, height, format,
-      (producer_usage | consumer_usage), user_metadata_size);
-  if (!status) {
-    ALOGE(
-        "BufferProducer::BufferProducer: Failed to create/get persistent "
-        "buffer \"%s\": %s",
-        name.c_str(), status.GetErrorMessage().c_str());
-    Close(-status.error());
-    return;
-  }
-
-  const int ret = ImportBuffer();
-  if (ret < 0) {
-    ALOGE(
-        "BufferProducer::BufferProducer: Failed to import producer buffer "
-        "\"%s\": %s",
-        name.c_str(), strerror(-ret));
-    Close(ret);
-  }
-}
-
 BufferProducer::BufferProducer(uint32_t usage, size_t size)
     : BufferProducer(usage, usage, size) {}
 
@@ -511,73 +467,6 @@
   }
 }
 
-BufferProducer::BufferProducer(const std::string& name, int user_id,
-                               int group_id, uint32_t usage, size_t size)
-    : BufferProducer(name, user_id, group_id, usage, usage, size) {}
-
-BufferProducer::BufferProducer(const std::string& name, int user_id,
-                               int group_id, uint64_t producer_usage,
-                               uint64_t consumer_usage, size_t size)
-    : BASE(BufferHubRPC::kClientPath) {
-  ATRACE_NAME("BufferProducer::BufferProducer");
-  ALOGD_IF(TRACE,
-           "BufferProducer::BufferProducer: name=%s user_id=%d group=%d "
-           "producer_usage=%" PRIx64 " consumer_usage=%" PRIx64 " size=%zu",
-           name.c_str(), user_id, group_id, producer_usage, consumer_usage,
-           size);
-  const int width = static_cast<int>(size);
-  const int height = 1;
-  const int format = HAL_PIXEL_FORMAT_BLOB;
-  const size_t user_metadata_size = 0;
-
-  // (b/37881101) Deprecate producer/consumer usage
-  auto status = InvokeRemoteMethod<BufferHubRPC::CreatePersistentBuffer>(
-      name, user_id, group_id, width, height, format,
-      (producer_usage | consumer_usage), user_metadata_size);
-  if (!status) {
-    ALOGE(
-        "BufferProducer::BufferProducer: Failed to create persistent "
-        "buffer \"%s\": %s",
-        name.c_str(), status.GetErrorMessage().c_str());
-    Close(-status.error());
-    return;
-  }
-
-  const int ret = ImportBuffer();
-  if (ret < 0) {
-    ALOGE(
-        "BufferProducer::BufferProducer: Failed to import producer buffer "
-        "\"%s\": %s",
-        name.c_str(), strerror(-ret));
-    Close(ret);
-  }
-}
-
-BufferProducer::BufferProducer(const std::string& name)
-    : BASE(BufferHubRPC::kClientPath) {
-  ATRACE_NAME("BufferProducer::BufferProducer");
-  ALOGD_IF(TRACE, "BufferProducer::BufferProducer: name=%s", name.c_str());
-
-  auto status = InvokeRemoteMethod<BufferHubRPC::GetPersistentBuffer>(name);
-  if (!status) {
-    ALOGE(
-        "BufferProducer::BufferProducer: Failed to get producer buffer by name "
-        "\"%s\": %s",
-        name.c_str(), status.GetErrorMessage().c_str());
-    Close(-status.error());
-    return;
-  }
-
-  const int ret = ImportBuffer();
-  if (ret < 0) {
-    ALOGE(
-        "BufferProducer::BufferProducer: Failed to import producer buffer "
-        "\"%s\": %s",
-        name.c_str(), strerror(-ret));
-    Close(ret);
-  }
-}
-
 BufferProducer::BufferProducer(LocalChannelHandle channel)
     : BASE(std::move(channel)) {
   const int ret = ImportBuffer();
@@ -736,19 +625,5 @@
                        : LocalChannelHandle{nullptr, -status.error()});
 }
 
-int BufferProducer::MakePersistent(const std::string& name, int user_id,
-                                   int group_id) {
-  ATRACE_NAME("BufferProducer::MakePersistent");
-  return ReturnStatusOrError(
-      InvokeRemoteMethod<BufferHubRPC::ProducerMakePersistent>(name, user_id,
-                                                               group_id));
-}
-
-int BufferProducer::RemovePersistence() {
-  ATRACE_NAME("BufferProducer::RemovePersistence");
-  return ReturnStatusOrError(
-      InvokeRemoteMethod<BufferHubRPC::ProducerRemovePersistence>());
-}
-
 }  // namespace dvr
 }  // namespace android
diff --git a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_client.h b/libs/vr/libbufferhub/include/private/dvr/buffer_hub_client.h
index a356959..8a4440f 100644
--- a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_client.h
+++ b/libs/vr/libbufferhub/include/private/dvr/buffer_hub_client.h
@@ -221,19 +221,6 @@
   // succeeded, or a negative errno code if local error check fails.
   int GainAsync(DvrNativeBufferMetadata* out_meta, LocalHandle* out_fence);
 
-  // Attaches the producer to |name| so that it becomes a persistent buffer that
-  // may be retrieved by name at a later time. This may be used in cases where a
-  // shared memory buffer should persist across the life of the producer process
-  // (i.e. the buffer may be held by clients across a service restart). The
-  // buffer may be associated with a user and/or group id to restrict access to
-  // the buffer. If user_id or group_id is -1 then checks for the respective id
-  // are disabled. If user_id or group_id is 0 then the respective id of the
-  // calling process is used instead.
-  int MakePersistent(const std::string& name, int user_id, int group_id);
-
-  // Removes the persistence of the producer.
-  int RemovePersistence();
-
  private:
   friend BASE;
 
@@ -248,40 +235,10 @@
                  uint64_t producer_usage, uint64_t consumer_usage,
                  size_t metadata_size);
 
-  // Constructs a persistent buffer with the given geometry and parameters and
-  // binds it to |name| in one shot. If a persistent buffer with the same name
-  // and settings already exists and matches the given geometry and parameters,
-  // that buffer is connected to this client instead of creating a new buffer.
-  // If the name matches but the geometry or settings do not match then
-  // construction fails and BufferProducer::Create() returns nullptr.
-  //
-  // Access to the persistent buffer may be restricted by |user_id| and/or
-  // |group_id|; these settings are established only when the buffer is first
-  // created and cannot be changed. A user or group id of -1 disables checks for
-  // that respective id. A user or group id of 0 is substituted with the
-  // effective user or group id of the calling process.
-  BufferProducer(const std::string& name, int user_id, int group_id,
-                 uint32_t width, uint32_t height, uint32_t format,
-                 uint32_t usage, size_t metadata_size = 0);
-  BufferProducer(const std::string& name, int user_id, int group_id,
-                 uint32_t width, uint32_t height, uint32_t format,
-                 uint64_t producer_usage, uint64_t consumer_usage,
-                 size_t user_metadata_size);
-
   // Constructs a blob (flat) buffer with the given usage flags.
   BufferProducer(uint32_t usage, size_t size);
   BufferProducer(uint64_t producer_usage, uint64_t consumer_usage, size_t size);
 
-  // Constructs a persistent blob (flat) buffer and binds it to |name|.
-  BufferProducer(const std::string& name, int user_id, int group_id,
-                 uint32_t usage, size_t size);
-  BufferProducer(const std::string& name, int user_id, int group_id,
-                 uint64_t producer_usage, uint64_t consumer_usage, size_t size);
-
-  // Constructs a channel to persistent buffer by name only. The buffer must
-  // have been previously created or made persistent.
-  explicit BufferProducer(const std::string& name);
-
   // Imports the given file handle to a producer channel, taking ownership.
   explicit BufferProducer(LocalChannelHandle channel);
 
diff --git a/libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h b/libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h
index f105b02..c70fffc 100644
--- a/libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h
+++ b/libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h
@@ -366,12 +366,8 @@
   // Op codes.
   enum {
     kOpCreateBuffer = 0,
-    kOpCreatePersistentBuffer,
-    kOpGetPersistentBuffer,
     kOpGetBuffer,
     kOpNewConsumer,
-    kOpProducerMakePersistent,
-    kOpProducerRemovePersistence,
     kOpProducerPost,
     kOpProducerGain,
     kOpConsumerAcquire,
@@ -394,19 +390,9 @@
   PDX_REMOTE_METHOD(CreateBuffer, kOpCreateBuffer,
                     void(uint32_t width, uint32_t height, uint32_t format,
                          uint64_t usage, size_t user_metadata_size));
-  PDX_REMOTE_METHOD(CreatePersistentBuffer, kOpCreatePersistentBuffer,
-                    void(const std::string& name, int user_id, int group_id,
-                         uint32_t width, uint32_t height, uint32_t format,
-                         uint64_t usage, size_t user_metadata_size));
-  PDX_REMOTE_METHOD(GetPersistentBuffer, kOpGetPersistentBuffer,
-                    void(const std::string& name));
   PDX_REMOTE_METHOD(GetBuffer, kOpGetBuffer,
                     BufferDescription<LocalHandle>(Void));
   PDX_REMOTE_METHOD(NewConsumer, kOpNewConsumer, LocalChannelHandle(Void));
-  PDX_REMOTE_METHOD(ProducerMakePersistent, kOpProducerMakePersistent,
-                    void(const std::string& name, int user_id, int group_id));
-  PDX_REMOTE_METHOD(ProducerRemovePersistence, kOpProducerRemovePersistence,
-                    void(Void));
   PDX_REMOTE_METHOD(ProducerPost, kOpProducerPost,
                     void(LocalFence acquire_fence));
   PDX_REMOTE_METHOD(ProducerGain, kOpProducerGain, LocalFence(Void));
diff --git a/libs/vr/libbufferhubqueue/buffer_hub_queue_client.cpp b/libs/vr/libbufferhubqueue/buffer_hub_queue_client.cpp
index c75c67f..8feb1cd 100644
--- a/libs/vr/libbufferhubqueue/buffer_hub_queue_client.cpp
+++ b/libs/vr/libbufferhubqueue/buffer_hub_queue_client.cpp
@@ -582,6 +582,12 @@
   return {std::move(queue_parcelable)};
 }
 
+/*static */
+std::unique_ptr<ConsumerQueue> ConsumerQueue::Import(
+    LocalChannelHandle handle) {
+  return std::unique_ptr<ConsumerQueue>(new ConsumerQueue(std::move(handle)));
+}
+
 ConsumerQueue::ConsumerQueue(LocalChannelHandle handle)
     : BufferHubQueue(std::move(handle)) {
   auto status = ImportQueue();
diff --git a/libs/vr/libbufferhubqueue/include/private/dvr/buffer_hub_queue_client.h b/libs/vr/libbufferhubqueue/include/private/dvr/buffer_hub_queue_client.h
index 8965530..60e1c4b 100644
--- a/libs/vr/libbufferhubqueue/include/private/dvr/buffer_hub_queue_client.h
+++ b/libs/vr/libbufferhubqueue/include/private/dvr/buffer_hub_queue_client.h
@@ -3,6 +3,14 @@
 
 #include <ui/BufferQueueDefs.h>
 
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Weverything"
+#endif
+
+// The following headers are included without checking every warning.
+// TODO(b/72172820): Remove the workaround once we have enforced -Weverything
+// in these headers and their dependencies.
 #include <pdx/client.h>
 #include <pdx/status.h>
 #include <private/dvr/buffer_hub_client.h>
@@ -10,6 +18,10 @@
 #include <private/dvr/bufferhub_rpc.h>
 #include <private/dvr/epoll_file_descriptor.h>
 
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+
 #include <memory>
 #include <queue>
 #include <vector>
@@ -45,10 +57,10 @@
   uint32_t default_width() const { return default_width_; }
 
   // Returns the default buffer height of this buffer queue.
-  uint32_t default_height() const { return default_height_; }
+  uint32_t default_height() const { return static_cast<uint32_t>(default_height_); }
 
   // Returns the default buffer format of this buffer queue.
-  uint32_t default_format() const { return default_format_; }
+  uint32_t default_format() const { return static_cast<uint32_t>(default_format_); }
 
   // Creates a new consumer in handle form for immediate transport over RPC.
   pdx::Status<pdx::LocalChannelHandle> CreateConsumerQueueHandle(
@@ -160,16 +172,16 @@
   // per-buffer data.
   struct Entry {
     Entry() : slot(0) {}
-    Entry(const std::shared_ptr<BufferHubBuffer>& buffer, size_t slot,
-          uint64_t index)
-        : buffer(buffer), slot(slot), index(index) {}
-    Entry(const std::shared_ptr<BufferHubBuffer>& buffer,
-          std::unique_ptr<uint8_t[]> metadata, pdx::LocalHandle fence,
-          size_t slot)
-        : buffer(buffer),
-          metadata(std::move(metadata)),
-          fence(std::move(fence)),
-          slot(slot) {}
+    Entry(const std::shared_ptr<BufferHubBuffer>& in_buffer, size_t in_slot,
+          uint64_t in_index)
+        : buffer(in_buffer), slot(in_slot), index(in_index) {}
+    Entry(const std::shared_ptr<BufferHubBuffer>& in_buffer,
+          std::unique_ptr<uint8_t[]> in_metadata, pdx::LocalHandle in_fence,
+          size_t in_slot)
+        : buffer(in_buffer),
+          metadata(std::move(in_metadata)),
+          fence(std::move(in_fence)),
+          slot(in_slot) {}
     Entry(Entry&&) = default;
     Entry& operator=(Entry&&) = default;
 
@@ -227,13 +239,13 @@
   bool is_async_{false};
 
   // Default buffer width that is set during ProducerQueue's creation.
-  size_t default_width_{1};
+  uint32_t default_width_{1};
 
   // Default buffer height that is set during ProducerQueue's creation.
-  size_t default_height_{1};
+  uint32_t default_height_{1};
 
   // Default buffer format that is set during ProducerQueue's creation.
-  int32_t default_format_{1};  // PIXEL_FORMAT_RGBA_8888
+  uint32_t default_format_{1};  // PIXEL_FORMAT_RGBA_8888
 
   // Tracks the buffers belonging to this queue. Buffers are stored according to
   // "slot" in this vector. Each slot is a logical id of the buffer within this
@@ -373,10 +385,7 @@
   // used to avoid participation in the buffer lifecycle by a consumer queue
   // that is only used to spawn other consumer queues, such as in an
   // intermediate service.
-  static std::unique_ptr<ConsumerQueue> Import(pdx::LocalChannelHandle handle) {
-    return std::unique_ptr<ConsumerQueue>(
-        new ConsumerQueue(std::move(handle)));
-  }
+  static std::unique_ptr<ConsumerQueue> Import(pdx::LocalChannelHandle handle);
 
   // Import newly created buffers from the service side.
   // Returns number of buffers successfully imported or an error.
diff --git a/libs/vr/libbufferhubqueue/include/private/dvr/buffer_hub_queue_parcelable.h b/libs/vr/libbufferhubqueue/include/private/dvr/buffer_hub_queue_parcelable.h
index 89baf92..4dea9b2 100644
--- a/libs/vr/libbufferhubqueue/include/private/dvr/buffer_hub_queue_parcelable.h
+++ b/libs/vr/libbufferhubqueue/include/private/dvr/buffer_hub_queue_parcelable.h
@@ -1,8 +1,20 @@
 #ifndef ANDROID_DVR_BUFFER_HUB_QUEUE_PARCELABLE_H_
 #define ANDROID_DVR_BUFFER_HUB_QUEUE_PARCELABLE_H_
 
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Weverything"
+#endif
+
+// The following headers are included without checking every warning.
+// TODO(b/72172820): Remove the workaround once we have enforced -Weverything
+// in these headers and their dependencies.
 #include <pdx/channel_parcelable.h>
 
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+
 namespace android {
 namespace dvr {
 
@@ -17,8 +29,10 @@
   BufferHubQueueParcelable() = default;
 
   BufferHubQueueParcelable(BufferHubQueueParcelable&& other) = default;
-  BufferHubQueueParcelable& operator=(BufferHubQueueParcelable&& other) =
-      default;
+  BufferHubQueueParcelable& operator=(BufferHubQueueParcelable&& other) {
+    channel_parcelable_ = std::move(other.channel_parcelable_);
+    return *this;
+  }
 
   // Constructs an parcelable contains the channel parcelable.
   BufferHubQueueParcelable(
diff --git a/libs/vr/libdvr/tests/Android.bp b/libs/vr/libdvr/tests/Android.bp
index ac20760..1ae75fb 100644
--- a/libs/vr/libdvr/tests/Android.bp
+++ b/libs/vr/libdvr/tests/Android.bp
@@ -52,24 +52,3 @@
     ],
     name: "dvr_api-test",
 }
-
-cc_test {
-    srcs: [
-        "dvr_buffer_queue-test.cpp",
-    ],
-
-    header_libs: [
-        "libdvr_headers",
-        "libbase_headers",
-    ],
-    shared_libs: [
-        "liblog",
-        "libnativewindow",
-    ],
-    cflags: [
-        "-DTRACE=0",
-        "-O0",
-        "-g",
-    ],
-    name: "dvr_buffer_queue-test",
-}
diff --git a/libs/vr/libdvr/tests/Android.mk b/libs/vr/libdvr/tests/Android.mk
new file mode 100644
index 0000000..0f3840d
--- /dev/null
+++ b/libs/vr/libdvr/tests/Android.mk
@@ -0,0 +1,73 @@
+# Copyright (C) 2018 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+# TODO(b/73133405): Currently, building cc_test against NDK using Android.bp
+# doesn't work well. Migrate to use Android.bp once b/73133405 gets fixed.
+
+include $(CLEAR_VARS)
+LOCAL_MODULE:= dvr_buffer_queue-test
+
+# Includes the dvr_api.h header. Tests should only include "dvr_api.h",
+# and shall only get access to |dvrGetApi|, as other symbols are hidden from the
+# library.
+LOCAL_C_INCLUDES := \
+    frameworks/native/libs/vr/libdvr/include \
+
+LOCAL_SANITIZE := thread
+
+LOCAL_SRC_FILES := dvr_buffer_queue-test.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+    libandroid \
+    liblog \
+
+LOCAL_CFLAGS := \
+    -DTRACE=0 \
+    -O2 \
+    -g \
+
+# DTS Should only link to NDK libraries.
+LOCAL_SDK_VERSION := 26
+LOCAL_NDK_STL_VARIANT := c++_static
+
+include $(BUILD_NATIVE_TEST)
+
+
+include $(CLEAR_VARS)
+LOCAL_MODULE:= dvr_display-test
+
+LOCAL_C_INCLUDES := \
+    frameworks/native/libs/vr/libdvr/include \
+    frameworks/native/libs/nativewindow/include
+
+LOCAL_SANITIZE := thread
+
+LOCAL_SRC_FILES := dvr_display-test.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+    libandroid \
+    liblog
+
+LOCAL_CFLAGS := \
+    -DTRACE=0 \
+    -O2 \
+    -g
+
+# DTS Should only link to NDK libraries.
+LOCAL_SDK_VERSION := 26
+LOCAL_NDK_STL_VARIANT := c++_static
+
+include $(BUILD_NATIVE_TEST)
\ No newline at end of file
diff --git a/libs/vr/libdvr/tests/dvr_api_test.h b/libs/vr/libdvr/tests/dvr_api_test.h
new file mode 100644
index 0000000..648af75
--- /dev/null
+++ b/libs/vr/libdvr/tests/dvr_api_test.h
@@ -0,0 +1,38 @@
+#include <dlfcn.h>
+#include <dvr/dvr_api.h>
+
+#include <gtest/gtest.h>
+
+#define ASSERT_NOT_NULL(x) ASSERT_TRUE((x) != nullptr)
+
+/** DvrTestBase loads the libdvr.so at runtime and get the Dvr API version 1. */
+class DvrApiTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    int flags = RTLD_NOW | RTLD_LOCAL;
+
+    // Here we need to ensure that libdvr is loaded with RTLD_NODELETE flag set
+    // (so that calls to `dlclose` don't actually unload the library). This is a
+    // workaround for an Android NDK bug. See more detail:
+    // https://github.com/android-ndk/ndk/issues/360
+    flags |= RTLD_NODELETE;
+    platform_handle_ = dlopen("libdvr.so", flags);
+    ASSERT_NOT_NULL(platform_handle_) << "Dvr shared library missing.";
+
+    auto dvr_get_api = reinterpret_cast<decltype(&dvrGetApi)>(
+        dlsym(platform_handle_, "dvrGetApi"));
+    ASSERT_NOT_NULL(dvr_get_api) << "Platform library missing dvrGetApi.";
+
+    ASSERT_EQ(dvr_get_api(&api_, sizeof(api_), /*version=*/1), 0)
+        << "Unable to find compatible Dvr API.";
+  }
+
+  void TearDown() override {
+    if (platform_handle_ != nullptr) {
+      dlclose(platform_handle_);
+    }
+  }
+
+  void* platform_handle_ = nullptr;
+  DvrApi_v1 api_;
+};
diff --git a/libs/vr/libdvr/tests/dvr_buffer_queue-test.cpp b/libs/vr/libdvr/tests/dvr_buffer_queue-test.cpp
index adf6977..301458a 100644
--- a/libs/vr/libdvr/tests/dvr_buffer_queue-test.cpp
+++ b/libs/vr/libdvr/tests/dvr_buffer_queue-test.cpp
@@ -1,7 +1,5 @@
-#include <android-base/unique_fd.h>
 #include <android/log.h>
 #include <android/native_window.h>
-#include <dlfcn.h>
 #include <dvr/dvr_api.h>
 #include <dvr/dvr_buffer_queue.h>
 
@@ -10,14 +8,14 @@
 #include <array>
 #include <unordered_map>
 
+#include "dvr_api_test.h"
+
 #define LOG_TAG "dvr_buffer_queue-test"
 
 #ifndef ALOGD
 #define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
 #endif
 
-#define ASSERT_NOT_NULL(x) ASSERT_TRUE((x) != nullptr)
-
 #ifndef ALOGD_IF
 #define ALOGD_IF(cond, ...) \
   ((__predict_false(cond)) ? ((void)ALOGD(__VA_ARGS__)) : (void)0)
@@ -32,7 +30,7 @@
 static constexpr uint64_t kBufferUsage = AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN;
 static constexpr size_t kQueueCapacity = 3;
 
-class DvrBufferQueueTest : public ::testing::Test {
+class DvrBufferQueueTest : public DvrApiTest {
  public:
   static void BufferAvailableCallback(void* context) {
     DvrBufferQueueTest* thiz = static_cast<DvrBufferQueueTest*>(context);
@@ -45,26 +43,12 @@
   }
 
  protected:
-  void SetUp() override {
-    platform_handle_ = dlopen("libdvr.so", RTLD_NOW | RTLD_LOCAL);
-    ASSERT_NOT_NULL(platform_handle_) << "Dvr shared library missing.";
-
-    auto dvr_get_api = reinterpret_cast<decltype(&dvrGetApi)>(
-        dlsym(platform_handle_, "dvrGetApi"));
-    ASSERT_NOT_NULL(dvr_get_api) << "Platform library missing dvrGetApi.";
-
-    ASSERT_EQ(dvr_get_api(&api_, sizeof(api_), /*version=*/1), 0)
-        << "Unable to find compatible Dvr API.";
-  }
-
   void TearDown() override {
     if (write_queue_ != nullptr) {
       api_.WriteBufferQueueDestroy(write_queue_);
       write_queue_ = nullptr;
     }
-    if (platform_handle_ != nullptr) {
-      dlclose(platform_handle_);
-    }
+    DvrApiTest::TearDown();
   }
 
   void HandleBufferAvailable() {
@@ -81,8 +65,6 @@
   DvrWriteBufferQueue* write_queue_{nullptr};
   int buffer_available_count_{0};
   int buffer_removed_count_{0};
-  void* platform_handle_{nullptr};
-  DvrApi_v1 api_{};
 };
 
 TEST_F(DvrBufferQueueTest, WriteQueueCreateDestroy) {
@@ -192,7 +174,7 @@
   ASSERT_TRUE(api_.WriteBufferIsValid(wb));
   ALOGD_IF(TRACE, "TestDequeuePostDequeueRelease, gain buffer %p, fence_fd=%d",
            wb, fence_fd);
-  android::base::unique_fd release_fence(fence_fd);
+  close(fence_fd);
 
   // Post buffer to the read_queue.
   meta1.timestamp = 42;
@@ -217,7 +199,7 @@
   ALOGD_IF(TRACE,
            "TestDequeuePostDequeueRelease, acquire buffer %p, fence_fd=%d", rb,
            fence_fd);
-  android::base::unique_fd acquire_fence(fence_fd);
+  close(fence_fd);
 
   // Release buffer to the write_queue.
   ret = api_.ReadBufferQueueReleaseBuffer(read_queue, rb, &meta2,
@@ -304,7 +286,7 @@
   ASSERT_EQ(0, ret);
   ASSERT_TRUE(api_.WriteBufferIsValid(wb1));
   ALOGD_IF(TRACE, "TestResizeBuffer, gain buffer %p", wb1);
-  android::base::unique_fd release_fence1(fence_fd);
+  close(fence_fd);
 
   // Check the buffer dimension.
   ret = api_.WriteBufferGetAHardwareBuffer(wb1, &ahb1);
@@ -332,7 +314,7 @@
   ASSERT_TRUE(api_.WriteBufferIsValid(wb2));
   ALOGD_IF(TRACE, "TestResizeBuffer, gain buffer %p, fence_fd=%d", wb2,
            fence_fd);
-  android::base::unique_fd release_fence2(fence_fd);
+  close(fence_fd);
 
   // Check the buffer dimension, should be new width
   ret = api_.WriteBufferGetAHardwareBuffer(wb2, &ahb2);
@@ -359,7 +341,7 @@
   ASSERT_TRUE(api_.WriteBufferIsValid(wb3));
   ALOGD_IF(TRACE, "TestResizeBuffer, gain buffer %p, fence_fd=%d", wb3,
            fence_fd);
-  android::base::unique_fd release_fence3(fence_fd);
+  close(fence_fd);
 
   // Check the buffer dimension, should be new width
   ret = api_.WriteBufferGetAHardwareBuffer(wb3, &ahb3);
diff --git a/libs/vr/libdvr/tests/dvr_display-test.cpp b/libs/vr/libdvr/tests/dvr_display-test.cpp
new file mode 100644
index 0000000..1165573
--- /dev/null
+++ b/libs/vr/libdvr/tests/dvr_display-test.cpp
@@ -0,0 +1,121 @@
+#include <android/hardware_buffer.h>
+#include <android/log.h>
+#include <dvr/dvr_api.h>
+#include <dvr/dvr_display_types.h>
+#include <dvr/dvr_surface.h>
+
+#include <gtest/gtest.h>
+
+#include "dvr_api_test.h"
+
+#define LOG_TAG "dvr_display-test"
+
+#ifndef ALOGD
+#define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
+#endif
+
+class DvrDisplayTest : public DvrApiTest {
+ protected:
+  void TearDown() override {
+    if (write_queue_ != nullptr) {
+      api_.WriteBufferQueueDestroy(write_queue_);
+      write_queue_ = nullptr;
+    }
+    DvrApiTest::TearDown();
+  }
+
+  DvrWriteBufferQueue* write_queue_ = nullptr;
+};
+
+TEST_F(DvrDisplayTest, DisplaySingleColor) {
+  // Create direct surface.
+  DvrSurface* direct_surface = nullptr;
+  std::vector<DvrSurfaceAttribute> direct_surface_attributes = {
+      {.key = DVR_SURFACE_ATTRIBUTE_DIRECT,
+       .value.type = DVR_SURFACE_ATTRIBUTE_TYPE_BOOL,
+       .value.bool_value = true},
+      {.key = DVR_SURFACE_ATTRIBUTE_Z_ORDER,
+       .value.type = DVR_SURFACE_ATTRIBUTE_TYPE_INT32,
+       .value.int32_value = 10},
+      {.key = DVR_SURFACE_ATTRIBUTE_VISIBLE,
+       .value.type = DVR_SURFACE_ATTRIBUTE_TYPE_BOOL,
+       .value.bool_value = true},
+  };
+  int ret =
+      api_.SurfaceCreate(direct_surface_attributes.data(),
+                         direct_surface_attributes.size(), &direct_surface);
+  ASSERT_EQ(ret, 0) << "Failed to create direct surface.";
+
+  // Get screen dimension.
+  DvrNativeDisplayMetrics display_metrics;
+  ret = api_.GetNativeDisplayMetrics(sizeof(display_metrics), &display_metrics);
+  ASSERT_EQ(ret, 0) << "Failed to get display metrics.";
+  ALOGD(
+      "display_width: %d, display_height: %d, display_x_dpi: %d, "
+      "display_y_dpi: %d, vsync_period_ns: %d.",
+      display_metrics.display_width, display_metrics.display_height,
+      display_metrics.display_x_dpi, display_metrics.display_y_dpi,
+      display_metrics.vsync_period_ns);
+
+  // Create a buffer queue with the direct surface.
+  constexpr uint32_t kLayerCount = 1;
+  constexpr uint64_t kUsage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
+                              AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT |
+                              AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN;
+  constexpr uint32_t kFormat = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;
+  constexpr size_t kCapacity = 1;
+  constexpr size_t kMetadataSize = 0;
+  uint32_t width = display_metrics.display_width;
+  uint32_t height = display_metrics.display_height;
+  ret = api_.SurfaceCreateWriteBufferQueue(
+      direct_surface, width, height, kFormat, kLayerCount, kUsage, kCapacity,
+      kMetadataSize, &write_queue_);
+  EXPECT_EQ(0, ret) << "Failed to create buffer queue.";
+  ASSERT_NOT_NULL(write_queue_) << "Write buffer queue should not be null.";
+
+  // Get buffer from WriteBufferQueue.
+  DvrWriteBuffer* write_buffer = nullptr;
+  constexpr int kTimeoutMs = 1000;
+  DvrNativeBufferMetadata out_meta;
+  int out_fence_fd = -1;
+  ret = api_.WriteBufferQueueGainBuffer(write_queue_, kTimeoutMs, &write_buffer,
+                                        &out_meta, &out_fence_fd);
+  EXPECT_EQ(0, ret) << "Failed to get the buffer.";
+  ASSERT_NOT_NULL(write_buffer) << "Gained buffer should not be null.";
+
+  // Convert to an android hardware buffer.
+  AHardwareBuffer* ah_buffer{nullptr};
+  ret = api_.WriteBufferGetAHardwareBuffer(write_buffer, &ah_buffer);
+  EXPECT_EQ(0, ret) << "Failed to get a hardware buffer from the write buffer.";
+  ASSERT_NOT_NULL(ah_buffer) << "AHardware buffer should not be null.";
+
+  // Change the content of the android hardware buffer.
+  void* buffer_data{nullptr};
+  int32_t fence = -1;
+  ret = AHardwareBuffer_lock(ah_buffer, AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN,
+                             fence, nullptr, &buffer_data);
+  EXPECT_EQ(0, ret) << "Failed to lock the hardware buffer.";
+  ASSERT_NOT_NULL(buffer_data) << "Buffer data should not be null.";
+
+  uint32_t color_texture = 0xff0000ff;  // Red color in RGBA.
+  for (uint32_t i = 0; i < width * height; ++i) {
+    memcpy(reinterpret_cast<void*>(reinterpret_cast<int64_t>(buffer_data) +
+                                   i * sizeof(color_texture)),
+           &color_texture, sizeof(color_texture));
+  }
+
+  fence = -1;
+  ret = AHardwareBuffer_unlock(ah_buffer, &fence);
+  EXPECT_EQ(0, ret) << "Failed to unlock the hardware buffer.";
+
+  // Release the android hardware buffer.
+  AHardwareBuffer_release(ah_buffer);
+
+  // Post buffer.
+  int ready_fence_fd = -1;
+  ret = api_.WriteBufferQueuePostBuffer(write_queue_, write_buffer, &out_meta,
+                                        ready_fence_fd);
+  EXPECT_EQ(0, ret) << "Failed to post the buffer.";
+
+  sleep(5);  // For visual check on the device under test.
+}
diff --git a/libs/vr/libpdx/service_tests.cpp b/libs/vr/libpdx/service_tests.cpp
index c7412b7..e623abf 100644
--- a/libs/vr/libpdx/service_tests.cpp
+++ b/libs/vr/libpdx/service_tests.cpp
@@ -180,8 +180,8 @@
   EXPECT_EQ(kTestTid, message.GetThreadId());
   EXPECT_EQ(kTestCid, message.GetChannelId());
   EXPECT_EQ(kTestMid, message.GetMessageId());
-  EXPECT_EQ(kTestEuid, message.GetEffectiveUserId());
-  EXPECT_EQ(kTestEgid, message.GetEffectiveGroupId());
+  EXPECT_EQ((unsigned) kTestEuid, message.GetEffectiveUserId());
+  EXPECT_EQ((unsigned) kTestEgid, message.GetEffectiveGroupId());
   EXPECT_EQ(kTestOp, message.GetOp());
   EXPECT_EQ(service_, message.GetService());
   EXPECT_EQ(test_channel, message.GetChannel());
diff --git a/opengl/libagl/BufferObjectManager.cpp b/opengl/libagl/BufferObjectManager.cpp
index 6bf28ee..3d93c19 100644
--- a/opengl/libagl/BufferObjectManager.cpp
+++ b/opengl/libagl/BufferObjectManager.cpp
@@ -18,7 +18,7 @@
 #include <stddef.h>
 #include <sys/types.h>
 
-#include <utils/Atomic.h>
+#include <cutils/atomic.h>
 #include <utils/RefBase.h>
 #include <utils/KeyedVector.h>
 #include <utils/Errors.h>
diff --git a/opengl/libagl/TextureObjectManager.h b/opengl/libagl/TextureObjectManager.h
index de9e03e..9cf8771 100644
--- a/opengl/libagl/TextureObjectManager.h
+++ b/opengl/libagl/TextureObjectManager.h
@@ -21,7 +21,7 @@
 #include <stddef.h>
 #include <sys/types.h>
 
-#include <utils/Atomic.h>
+#include <cutils/atomic.h>
 #include <utils/threads.h>
 #include <utils/RefBase.h>
 #include <utils/KeyedVector.h>
diff --git a/opengl/libs/EGL/eglApi.cpp b/opengl/libs/EGL/eglApi.cpp
index b00602c..46e7a97 100644
--- a/opengl/libs/EGL/eglApi.cpp
+++ b/opengl/libs/EGL/eglApi.cpp
@@ -2006,22 +2006,13 @@
     egl_display_ptr dp = validate_display(dpy);
     if (!dp) return EGL_NO_SURFACE;
 
-    EGLint colorSpace = EGL_GL_COLORSPACE_LINEAR_KHR;
-    android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
-    // TODO: Probably need to update EGL_KHR_stream_producer_eglsurface to
-    // indicate support for EGL_GL_COLORSPACE_KHR.
-    // now select a corresponding sRGB format if needed
-    if (!getColorSpaceAttribute(dp, attrib_list, colorSpace, dataSpace)) {
-        ALOGE("error invalid colorspace: %d", colorSpace);
-        return setError(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
-    }
-
     egl_connection_t* const cnx = &gEGLImpl;
     if (cnx->dso && cnx->egl.eglCreateStreamProducerSurfaceKHR) {
         EGLSurface surface = cnx->egl.eglCreateStreamProducerSurfaceKHR(
                 dp->disp.dpy, config, stream, attrib_list);
         if (surface != EGL_NO_SURFACE) {
-            egl_surface_t* s = new egl_surface_t(dp.get(), config, NULL, surface, colorSpace, cnx);
+            egl_surface_t* s = new egl_surface_t(dp.get(), config, NULL, surface,
+                                                 EGL_GL_COLORSPACE_LINEAR_KHR, cnx);
             return s;
         }
     }
diff --git a/opengl/tests/gl2_java/Android.mk b/opengl/tests/gl2_java/Android.mk
index 34f4aee..71aa5a0 100644
--- a/opengl/tests/gl2_java/Android.mk
+++ b/opengl/tests/gl2_java/Android.mk
@@ -14,5 +14,6 @@
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 
 LOCAL_PACKAGE_NAME := GL2Java
+LOCAL_SDK_VERSION := current
 
 include $(BUILD_PACKAGE)
diff --git a/opengl/tests/gl2_jni/Android.mk b/opengl/tests/gl2_jni/Android.mk
index 409bd73..af65b5f 100644
--- a/opengl/tests/gl2_jni/Android.mk
+++ b/opengl/tests/gl2_jni/Android.mk
@@ -14,6 +14,7 @@
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 
 LOCAL_PACKAGE_NAME := GL2JNI
+LOCAL_SDK_VERSION := current
 
 LOCAL_JNI_SHARED_LIBRARIES := libgl2jni
 
diff --git a/opengl/tests/gl_jni/Android.mk b/opengl/tests/gl_jni/Android.mk
index 11b4c8b..570ae2b 100644
--- a/opengl/tests/gl_jni/Android.mk
+++ b/opengl/tests/gl_jni/Android.mk
@@ -14,6 +14,7 @@
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 
 LOCAL_PACKAGE_NAME := GLJNI
+LOCAL_SDK_VERSION := current
 
 LOCAL_JNI_SHARED_LIBRARIES := libgljni
 
diff --git a/opengl/tests/gldual/Android.mk b/opengl/tests/gldual/Android.mk
index 1991ed9..dc265b6 100644
--- a/opengl/tests/gldual/Android.mk
+++ b/opengl/tests/gldual/Android.mk
@@ -14,6 +14,7 @@
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 
 LOCAL_PACKAGE_NAME := GLDual
+LOCAL_SDK_VERSION := current
 
 LOCAL_JNI_SHARED_LIBRARIES := libgldualjni
 
diff --git a/opengl/tests/lighting1709/Android.mk b/opengl/tests/lighting1709/Android.mk
index 9563e61..0047231 100644
--- a/opengl/tests/lighting1709/Android.mk
+++ b/opengl/tests/lighting1709/Android.mk
@@ -6,6 +6,7 @@
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 
 LOCAL_PACKAGE_NAME := LightingTest
+LOCAL_SDK_VERSION := current
 LOCAL_CERTIFICATE := platform
 
 include $(BUILD_PACKAGE)
diff --git a/opengl/tests/testFramerate/Android.mk b/opengl/tests/testFramerate/Android.mk
index 500abf3..ca6654a 100644
--- a/opengl/tests/testFramerate/Android.mk
+++ b/opengl/tests/testFramerate/Android.mk
@@ -15,5 +15,6 @@
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 
 LOCAL_PACKAGE_NAME := TestFramerate
+LOCAL_SDK_VERSION := system_current
 
 include $(BUILD_PACKAGE)
diff --git a/opengl/tests/testPauseResume/Android.mk b/opengl/tests/testPauseResume/Android.mk
index cf8bdc3..dda5424 100644
--- a/opengl/tests/testPauseResume/Android.mk
+++ b/opengl/tests/testPauseResume/Android.mk
@@ -14,5 +14,6 @@
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 
 LOCAL_PACKAGE_NAME := TestEGL
+LOCAL_SDK_VERSION := current
 
 include $(BUILD_PACKAGE)
diff --git a/services/media/arcvideobridge/Android.bp b/services/media/arcvideobridge/Android.bp
index ed0f613..ca5b896 100644
--- a/services/media/arcvideobridge/Android.bp
+++ b/services/media/arcvideobridge/Android.bp
@@ -5,14 +5,13 @@
             srcs: [
                 "IArcVideoBridge.cpp",
             ],
-            // TODO: remove the suffix "_bp" after finishing migration to Android.bp.
             shared_libs: [
                 "libarcbridge",
                 "libarcbridgeservice",
                 "libbinder",
                 "libchrome",
                 "liblog",
-                "libmojo_bp",
+                "libmojo",
                 "libutils",
             ],
             cflags: [
diff --git a/services/sensorservice/BatteryService.cpp b/services/sensorservice/BatteryService.cpp
index 330861d..d8e5b29 100644
--- a/services/sensorservice/BatteryService.cpp
+++ b/services/sensorservice/BatteryService.cpp
@@ -18,7 +18,7 @@
 #include <math.h>
 #include <sys/types.h>
 
-#include <utils/Atomic.h>
+#include <cutils/atomic.h>
 #include <utils/Errors.h>
 #include <utils/Singleton.h>
 
diff --git a/services/sensorservice/SensorDevice.cpp b/services/sensorservice/SensorDevice.cpp
index fdb69d3..115a983 100644
--- a/services/sensorservice/SensorDevice.cpp
+++ b/services/sensorservice/SensorDevice.cpp
@@ -18,7 +18,7 @@
 
 #include <android-base/logging.h>
 #include <sensors/convert.h>
-#include <utils/Atomic.h>
+#include <cutils/atomic.h>
 #include <utils/Errors.h>
 #include <utils/Singleton.h>
 
diff --git a/services/surfaceflinger/Client.cpp b/services/surfaceflinger/Client.cpp
index a69940a..0c9f0e2 100644
--- a/services/surfaceflinger/Client.cpp
+++ b/services/surfaceflinger/Client.cpp
@@ -47,12 +47,21 @@
 
 Client::~Client()
 {
+    // We need to post a message to remove our remaining layers rather than
+    // do so directly by acquiring the SurfaceFlinger lock. If we were to
+    // attempt to directly call the lock it becomes effectively impossible
+    // to use sp<Client> while holding the SF lock as descoping it could
+    // then trigger a dead-lock.
+
     const size_t count = mLayers.size();
     for (size_t i=0 ; i<count ; i++) {
         sp<Layer> l = mLayers.valueAt(i).promote();
-        if (l != nullptr) {
-            mFlinger->removeLayer(l);
+        if (l == nullptr) {
+            continue;
         }
+        mFlinger->postMessageAsync(new LambdaMessage([flinger = mFlinger, l]() {
+            flinger->removeLayer(l);
+        }));
     }
 }
 
diff --git a/services/surfaceflinger/DisplayHardware/HWC2.cpp b/services/surfaceflinger/DisplayHardware/HWC2.cpp
index bcba35f..814b55e 100644
--- a/services/surfaceflinger/DisplayHardware/HWC2.cpp
+++ b/services/surfaceflinger/DisplayHardware/HWC2.cpp
@@ -617,9 +617,11 @@
 // For use by Device
 
 void Display::setConnected(bool connected) {
-    if (!mIsConnected && connected && mType == DisplayType::Physical) {
+    if (!mIsConnected && connected) {
         mComposer.setClientTargetSlotCount(mId);
-        loadConfigs();
+        if (mType == DisplayType::Physical) {
+            loadConfigs();
+        }
     }
     mIsConnected = connected;
 }
diff --git a/services/surfaceflinger/DisplayHardware/HWComposer.h b/services/surfaceflinger/DisplayHardware/HWComposer.h
index abb0fcb..b75dc6a 100644
--- a/services/surfaceflinger/DisplayHardware/HWComposer.h
+++ b/services/surfaceflinger/DisplayHardware/HWComposer.h
@@ -58,6 +58,7 @@
 class NativeHandle;
 class Region;
 class String8;
+class TestableSurfaceFlinger;
 
 namespace Hwc2 {
 class Composer;
@@ -170,6 +171,9 @@
 
     std::optional<hwc2_display_t> getHwcDisplayId(int32_t displayId) const;
 private:
+    // For unit tests
+    friend TestableSurfaceFlinger;
+
     static const int32_t VIRTUAL_DISPLAY_ID_BASE = 2;
 
     bool isValidDisplay(int32_t displayId) const;
diff --git a/services/surfaceflinger/EventThread.cpp b/services/surfaceflinger/EventThread.cpp
index 90aab50..1f4f5a5 100644
--- a/services/surfaceflinger/EventThread.cpp
+++ b/services/surfaceflinger/EventThread.cpp
@@ -100,8 +100,7 @@
     return NO_ERROR;
 }
 
-void EventThread::removeDisplayEventConnection(const wp<EventThread::Connection>& connection) {
-    std::lock_guard<std::mutex> lock(mMutex);
+void EventThread::removeDisplayEventConnectionLocked(const wp<EventThread::Connection>& connection) {
     mDisplayEventConnections.remove(connection);
 }
 
@@ -195,7 +194,7 @@
                 // handle any other error on the pipe as fatal. the only
                 // reasonable thing to do is to clean-up this connection.
                 // The most common error we'll get here is -EPIPE.
-                removeDisplayEventConnection(signalConnections[i]);
+                removeDisplayEventConnectionLocked(signalConnections[i]);
             }
         }
     }
diff --git a/services/surfaceflinger/EventThread.h b/services/surfaceflinger/EventThread.h
index 708806a..97f0a35 100644
--- a/services/surfaceflinger/EventThread.h
+++ b/services/surfaceflinger/EventThread.h
@@ -129,7 +129,7 @@
                                                            DisplayEventReceiver::Event* event)
             REQUIRES(mMutex);
 
-    void removeDisplayEventConnection(const wp<Connection>& connection);
+    void removeDisplayEventConnectionLocked(const wp<Connection>& connection) REQUIRES(mMutex);
     void enableVSyncLocked() REQUIRES(mMutex);
     void disableVSyncLocked() REQUIRES(mMutex);
 
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 03f6bdc..ea43c58 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -1289,6 +1289,11 @@
 
     mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
 
+    if (std::this_thread::get_id() == mMainThreadId) {
+        // Process all pending hot plug events immediately if we are on the main thread.
+        processDisplayHotplugEventsLocked();
+    }
+
     setTransactionFlags(eDisplayTransactionNeeded);
 }
 
@@ -2901,7 +2906,11 @@
 
 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
     Mutex::Autolock _l(mStateLock);
+    return removeLayerLocked(mStateLock, layer, topLevelOnly);
+}
 
+status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
+                                           bool topLevelOnly) {
     if (layer->isPendingRemoval()) {
         return NO_ERROR;
     }
@@ -2965,8 +2974,30 @@
     return old;
 }
 
+bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
+    for (const ComposerState& state : states) {
+        // Here we need to check that the interface we're given is indeed
+        // one of our own. A malicious client could give us a nullptr
+        // IInterface, or one of its own or even one of our own but a
+        // different type. All these situations would cause us to crash.
+        if (state.client == nullptr) {
+            return true;
+        }
+
+        sp<IBinder> binder = IInterface::asBinder(state.client);
+        if (binder == nullptr) {
+            return true;
+        }
+
+        if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
+            return true;
+        }
+    }
+    return false;
+}
+
 void SurfaceFlinger::setTransactionState(
-        const Vector<ComposerState>& state,
+        const Vector<ComposerState>& states,
         const Vector<DisplayState>& displays,
         uint32_t flags)
 {
@@ -2974,6 +3005,10 @@
     Mutex::Autolock _l(mStateLock);
     uint32_t transactionFlags = 0;
 
+    if (containsAnyInvalidClientState(states)) {
+        return;
+    }
+
     if (flags & eAnimation) {
         // For window updates that are part of an animation we must wait for
         // previous animation "frames" to be handled.
@@ -2990,31 +3025,20 @@
         }
     }
 
-    size_t count = displays.size();
-    for (size_t i=0 ; i<count ; i++) {
-        const DisplayState& s(displays[i]);
-        transactionFlags |= setDisplayStateLocked(s);
+    for (const DisplayState& display : displays) {
+        transactionFlags |= setDisplayStateLocked(display);
     }
 
-    count = state.size();
-    for (size_t i=0 ; i<count ; i++) {
-        const ComposerState& s(state[i]);
-        // Here we need to check that the interface we're given is indeed
-        // one of our own. A malicious client could give us a nullptr
-        // IInterface, or one of its own or even one of our own but a
-        // different type. All these situations would cause us to crash.
-        //
-        // NOTE: it would be better to use RTTI as we could directly check
-        // that we have a Client*. however, RTTI is disabled in Android.
-        if (s.client != nullptr) {
-            sp<IBinder> binder = IInterface::asBinder(s.client);
-            if (binder != nullptr) {
-                if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != nullptr) {
-                    sp<Client> client( static_cast<Client *>(s.client.get()) );
-                    transactionFlags |= setClientStateLocked(client, s.state);
-                }
-            }
-        }
+    for (const ComposerState& state : states) {
+        transactionFlags |= setClientStateLocked(state);
+    }
+
+    // Iterate through all layers again to determine if any need to be destroyed. Marking layers
+    // as destroyed should only occur after setting all other states. This is to allow for a
+    // child re-parent to happen before marking its original parent as destroyed (which would
+    // then mark the child as destroyed).
+    for (const ComposerState& state : states) {
+        setDestroyStateLocked(state);
     }
 
     // If a synchronous transaction is explicitly requested without any changes, force a transaction
@@ -3028,7 +3052,7 @@
 
     if (transactionFlags) {
         if (mInterceptor.isEnabled()) {
-            mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
+            mInterceptor.saveTransaction(states, mCurrentState.displays, displays, flags);
         }
 
         // this triggers the transaction
@@ -3105,10 +3129,10 @@
     return flags;
 }
 
-uint32_t SurfaceFlinger::setClientStateLocked(
-        const sp<Client>& client,
-        const layer_state_t& s)
-{
+uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
+    const layer_state_t& s = composerState.state;
+    sp<Client> client(static_cast<Client*>(composerState.client.get()));
+
     sp<Layer> layer(client->getLayerUser(s.surface));
     if (layer == nullptr) {
         return 0;
@@ -3259,6 +3283,25 @@
     return flags;
 }
 
+void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
+    const layer_state_t& state = composerState.state;
+    sp<Client> client(static_cast<Client*>(composerState.client.get()));
+
+    sp<Layer> layer(client->getLayerUser(state.surface));
+    if (layer == nullptr) {
+        return;
+    }
+
+    if (layer->isPendingRemoval()) {
+        ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
+        return;
+    }
+
+    if (state.what & layer_state_t::eDestroySurface) {
+        removeLayerLocked(mStateLock, layer);
+    }
+}
+
 status_t SurfaceFlinger::createLayer(
         const String8& name,
         const sp<Client>& client,
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index b7ebb1b..6da1409 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -26,8 +26,8 @@
  */
 
 #include <cutils/compiler.h>
+#include <cutils/atomic.h>
 
-#include <utils/Atomic.h>
 #include <utils/Errors.h>
 #include <utils/KeyedVector.h>
 #include <utils/RefBase.h>
@@ -473,8 +473,10 @@
     // Can only be called from the main thread or with mStateLock held
     uint32_t setTransactionFlags(uint32_t flags);
     void commitTransaction();
-    uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
+    bool containsAnyInvalidClientState(const Vector<ComposerState>& states);
+    uint32_t setClientStateLocked(const ComposerState& composerState);
     uint32_t setDisplayStateLocked(const DisplayState& s);
+    void setDestroyStateLocked(const ComposerState& composerState);
 
     /* ------------------------------------------------------------------------
      * Layer management
@@ -506,6 +508,7 @@
 
     // remove a layer from SurfaceFlinger immediately
     status_t removeLayer(const sp<Layer>& layer, bool topLevelOnly = false);
+    status_t removeLayerLocked(const Mutex&, const sp<Layer>& layer, bool topLevelOnly = false);
 
     // add a layer to SurfaceFlinger
     status_t addClientLayer(const sp<Client>& client,
diff --git a/services/surfaceflinger/tests/fakehwc/Android.bp b/services/surfaceflinger/tests/fakehwc/Android.bp
index 8e0ba83..00bc621 100644
--- a/services/surfaceflinger/tests/fakehwc/Android.bp
+++ b/services/surfaceflinger/tests/fakehwc/Android.bp
@@ -29,12 +29,12 @@
         "libutils",
     ],
     static_libs: [
-        "libhwcomposer-client",
         "libtrace_proto",
         "libgmock"
     ],
     header_libs: [
         "android.hardware.graphics.composer@2.1-command-buffer",
+        "android.hardware.graphics.composer@2.1-hal",
         "libsurfaceflinger_headers",
     ],
-}
\ No newline at end of file
+}
diff --git a/services/surfaceflinger/tests/fakehwc/FakeComposerClient.cpp b/services/surfaceflinger/tests/fakehwc/FakeComposerClient.cpp
index e16e7ec..973156a 100644
--- a/services/surfaceflinger/tests/fakehwc/FakeComposerClient.cpp
+++ b/services/surfaceflinger/tests/fakehwc/FakeComposerClient.cpp
@@ -145,8 +145,7 @@
 } // namespace
 
 FakeComposerClient::FakeComposerClient()
-      : mCallbacksOn(false),
-        mClient(nullptr),
+      : mEventCallback(nullptr),
         mCurrentConfig(NULL_DISPLAY_CONFIG),
         mVsyncEnabled(false),
         mLayers(),
@@ -160,30 +159,32 @@
     return false;
 }
 
-void FakeComposerClient::removeClient() {
-    ALOGV("removeClient");
-    // TODO: Ahooga! Only thing current lifetime management choices in
-    // APIs make possible. Sad.
-    delete this;
+std::string FakeComposerClient::dumpDebugInfo() {
+    return {};
 }
 
-void FakeComposerClient::enableCallback(bool enable) {
-    ALOGV("enableCallback");
-    mCallbacksOn = enable;
-    if (mCallbacksOn) {
-        mClient->onHotplug(PRIMARY_DISPLAY, IComposerCallback::Connection::CONNECTED);
+void FakeComposerClient::registerEventCallback(EventCallback* callback) {
+    ALOGV("registerEventCallback");
+    mEventCallback = callback;
+    if (mEventCallback) {
+        mEventCallback->onHotplug(PRIMARY_DISPLAY, IComposerCallback::Connection::CONNECTED);
     }
 }
 
+void FakeComposerClient::unregisterEventCallback() {
+    ALOGV("unregisterEventCallback");
+    mEventCallback = nullptr;
+}
+
 void FakeComposerClient::hotplugDisplay(Display display, IComposerCallback::Connection state) {
-    if (mCallbacksOn) {
-        mClient->onHotplug(display, state);
+    if (mEventCallback) {
+        mEventCallback->onHotplug(display, state);
     }
 }
 
 void FakeComposerClient::refreshDisplay(Display display) {
-    if (mCallbacksOn) {
-        mClient->onRefresh(display);
+    if (mEventCallback) {
+        mEventCallback->onRefresh(display);
     }
 }
 
@@ -500,12 +501,8 @@
 
 //////////////////////////////////////////////////////////////////
 
-void FakeComposerClient::setClient(ComposerClient* client) {
-    mClient = client;
-}
-
 void FakeComposerClient::requestVSync(uint64_t vsyncTime) {
-    if (mCallbacksOn) {
+    if (mEventCallback) {
         uint64_t timestamp = vsyncTime;
         ALOGV("Vsync");
         if (timestamp == 0) {
@@ -516,7 +513,7 @@
         if (mSurfaceComposer != nullptr) {
             mSurfaceComposer->injectVSync(timestamp);
         } else {
-            mClient->onVsync(PRIMARY_DISPLAY, timestamp);
+            mEventCallback->onVsync(PRIMARY_DISPLAY, timestamp);
         }
     }
 }
diff --git a/services/surfaceflinger/tests/fakehwc/FakeComposerClient.h b/services/surfaceflinger/tests/fakehwc/FakeComposerClient.h
index cef7f5b..d115d79 100644
--- a/services/surfaceflinger/tests/fakehwc/FakeComposerClient.h
+++ b/services/surfaceflinger/tests/fakehwc/FakeComposerClient.h
@@ -18,7 +18,7 @@
 
 #define HWC2_USE_CPP11
 #define HWC2_INCLUDE_STRINGIFICATION
-#include "ComposerClient.h"
+#include <composer-hal/2.1/ComposerClient.h>
 #undef HWC2_USE_CPP11
 #undef HWC2_INCLUDE_STRINGIFICATION
 #include "RenderState.h"
@@ -31,7 +31,7 @@
 #include <chrono>
 
 using namespace android::hardware::graphics::composer::V2_1;
-using namespace android::hardware::graphics::composer::V2_1::implementation;
+using namespace android::hardware::graphics::composer::V2_1::hal;
 using namespace android::hardware;
 using namespace std::chrono_literals;
 
@@ -54,15 +54,17 @@
 constexpr Display PRIMARY_DISPLAY = static_cast<Display>(HWC_DISPLAY_PRIMARY);
 constexpr Display EXTERNAL_DISPLAY = static_cast<Display>(HWC_DISPLAY_EXTERNAL);
 
-class FakeComposerClient : public ComposerBase {
+class FakeComposerClient : public ComposerHal {
 public:
     FakeComposerClient();
     virtual ~FakeComposerClient();
 
     bool hasCapability(hwc2_capability_t capability) override;
 
-    void removeClient() override;
-    void enableCallback(bool enable) override;
+    std::string dumpDebugInfo() override;
+    void registerEventCallback(EventCallback* callback) override;
+    void unregisterEventCallback() override;
+
     uint32_t getMaxVirtualDisplayCount() override;
     Error createVirtualDisplay(uint32_t width, uint32_t height, PixelFormat* format,
                                Display* outDisplay) override;
@@ -147,8 +149,7 @@
 private:
     LayerImpl& getLayerImpl(Layer handle);
 
-    bool mCallbacksOn;
-    ComposerClient* mClient;
+    EventCallback* mEventCallback;
     Config mCurrentConfig;
     bool mVsyncEnabled;
     std::vector<std::unique_ptr<LayerImpl>> mLayers;
diff --git a/services/surfaceflinger/tests/fakehwc/FakeComposerService.cpp b/services/surfaceflinger/tests/fakehwc/FakeComposerService.cpp
index c411604..f70cbdb 100644
--- a/services/surfaceflinger/tests/fakehwc/FakeComposerService.cpp
+++ b/services/surfaceflinger/tests/fakehwc/FakeComposerService.cpp
@@ -46,7 +46,9 @@
 
 Return<void> FakeComposerService::createClient(createClient_cb hidl_cb) {
     ALOGI("FakeComposerService::createClient %p", mClient.get());
-    mClient->initialize();
+    if (!mClient->init()) {
+        LOG_ALWAYS_FATAL("failed to initialize ComposerClient");
+    }
     hidl_cb(Error::NONE, mClient);
     return Void();
 }
diff --git a/services/surfaceflinger/tests/fakehwc/FakeComposerService.h b/services/surfaceflinger/tests/fakehwc/FakeComposerService.h
index 5204084..c439b7e 100644
--- a/services/surfaceflinger/tests/fakehwc/FakeComposerService.h
+++ b/services/surfaceflinger/tests/fakehwc/FakeComposerService.h
@@ -16,10 +16,10 @@
 
 #pragma once
 
-#include "ComposerClient.h"
+#include <composer-hal/2.1/ComposerClient.h>
 
 using namespace android::hardware::graphics::composer::V2_1;
-using namespace android::hardware::graphics::composer::V2_1::implementation;
+using namespace android::hardware::graphics::composer::V2_1::hal;
 using android::hardware::Return;
 
 namespace sftest {
diff --git a/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp b/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp
index 1873832..9b31985 100644
--- a/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp
+++ b/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp
@@ -168,8 +168,7 @@
     // interface instead of the current Composer interface might also
     // change the situation.
     mMockComposer = new MockComposerClient;
-    sp<ComposerClient> client = new ComposerClient(*mMockComposer);
-    mMockComposer->setClient(client.get());
+    sp<ComposerClient> client = new ComposerClient(mMockComposer);
     mFakeService = new FakeComposerService(client);
     (void)mFakeService->registerAsService("mock");
 
@@ -446,8 +445,7 @@
     // TODO: See TODO comment at DisplayTest::SetUp for background on
     // the lifetime of the FakeComposerClient.
     sFakeComposer = new FakeComposerClient;
-    sp<ComposerClient> client = new ComposerClient(*sFakeComposer);
-    sFakeComposer->setClient(client.get());
+    sp<ComposerClient> client = new ComposerClient(sFakeComposer);
     sp<IComposer> fakeService = new FakeComposerService(client);
     (void)fakeService->registerAsService("mock");
 
diff --git a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
index fc1b564..3841209 100644
--- a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
+++ b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
@@ -22,11 +22,29 @@
 
 #include <log/log.h>
 
+#include "MockComposer.h"
+#include "MockEventThread.h"
+#include "MockRenderEngine.h"
 #include "TestableSurfaceFlinger.h"
 
 namespace android {
 namespace {
 
+using testing::_;
+using testing::ByMove;
+using testing::DoAll;
+using testing::Mock;
+using testing::Return;
+using testing::SetArgPointee;
+
+using android::hardware::graphics::common::V1_0::Hdr;
+using android::Hwc2::Error;
+using android::Hwc2::IComposer;
+using android::Hwc2::IComposerClient;
+
+constexpr int32_t DEFAULT_REFRESH_RATE = 1666666666;
+constexpr int32_t DEFAULT_DPI = 320;
+
 class DisplayTransactionTest : public testing::Test {
 protected:
     DisplayTransactionTest();
@@ -36,12 +54,24 @@
     void setupPrimaryDisplay(int width, int height);
 
     TestableSurfaceFlinger mFlinger;
+    mock::EventThread* mEventThread = new mock::EventThread();
+
+    // These mocks are created by the test, but are destroyed by SurfaceFlinger
+    // by virtue of being stored into a std::unique_ptr. However we still need
+    // to keep a reference to them for use in setting up call expectations.
+    RE::mock::RenderEngine* mRenderEngine = new RE::mock::RenderEngine();
+    Hwc2::mock::Composer* mComposer = new Hwc2::mock::Composer();
 };
 
 DisplayTransactionTest::DisplayTransactionTest() {
     const ::testing::TestInfo* const test_info =
             ::testing::UnitTest::GetInstance()->current_test_info();
     ALOGD("**** Setting up for %s.%s\n", test_info->test_case_name(), test_info->name());
+
+    mFlinger.mutableEventThread().reset(mEventThread);
+    mFlinger.setupRenderEngine(std::unique_ptr<RE::RenderEngine>(mRenderEngine));
+
+    setupComposer(0);
 }
 
 DisplayTransactionTest::~DisplayTransactionTest() {
@@ -50,13 +80,92 @@
     ALOGD("**** Tearing down after %s.%s\n", test_info->test_case_name(), test_info->name());
 }
 
-TEST_F(DisplayTransactionTest, PlaceholderTrivialTest) {
-    auto result = mFlinger.getDefaultDisplayDeviceLocked();
-    EXPECT_EQ(nullptr, result.get());
+void DisplayTransactionTest::setupComposer(int virtualDisplayCount) {
+    EXPECT_CALL(*mComposer, getCapabilities())
+            .WillOnce(Return(std::vector<IComposer::Capability>()));
+    EXPECT_CALL(*mComposer, getMaxVirtualDisplayCount()).WillOnce(Return(virtualDisplayCount));
+    mFlinger.setupComposer(std::unique_ptr<Hwc2::Composer>(mComposer));
 
-    EXPECT_EQ(nullptr, mFlinger.mutableBuiltinDisplays()[0].get());
-    mFlinger.mutableBuiltinDisplays()[0] = new BBinder();
-    EXPECT_NE(nullptr, mFlinger.mutableBuiltinDisplays()[0].get());
+    Mock::VerifyAndClear(mComposer);
+}
+
+void DisplayTransactionTest::setupPrimaryDisplay(int width, int height) {
+    EXPECT_CALL(*mComposer, getDisplayType(DisplayDevice::DISPLAY_PRIMARY, _))
+            .WillOnce(DoAll(SetArgPointee<1>(IComposerClient::DisplayType::PHYSICAL),
+                            Return(Error::NONE)));
+    EXPECT_CALL(*mComposer, setClientTargetSlotCount(_)).WillOnce(Return(Error::NONE));
+    EXPECT_CALL(*mComposer, getDisplayConfigs(_, _))
+            .WillOnce(DoAll(SetArgPointee<1>(std::vector<unsigned>{0}), Return(Error::NONE)));
+    EXPECT_CALL(*mComposer,
+                getDisplayAttribute(DisplayDevice::DISPLAY_PRIMARY, 0,
+                                    IComposerClient::Attribute::WIDTH, _))
+            .WillOnce(DoAll(SetArgPointee<3>(width), Return(Error::NONE)));
+    EXPECT_CALL(*mComposer,
+                getDisplayAttribute(DisplayDevice::DISPLAY_PRIMARY, 0,
+                                    IComposerClient::Attribute::HEIGHT, _))
+            .WillOnce(DoAll(SetArgPointee<3>(height), Return(Error::NONE)));
+    EXPECT_CALL(*mComposer,
+                getDisplayAttribute(DisplayDevice::DISPLAY_PRIMARY, 0,
+                                    IComposerClient::Attribute::VSYNC_PERIOD, _))
+            .WillOnce(DoAll(SetArgPointee<3>(DEFAULT_REFRESH_RATE), Return(Error::NONE)));
+    EXPECT_CALL(*mComposer,
+                getDisplayAttribute(DisplayDevice::DISPLAY_PRIMARY, 0,
+                                    IComposerClient::Attribute::DPI_X, _))
+            .WillOnce(DoAll(SetArgPointee<3>(DEFAULT_DPI), Return(Error::NONE)));
+    EXPECT_CALL(*mComposer,
+                getDisplayAttribute(DisplayDevice::DISPLAY_PRIMARY, 0,
+                                    IComposerClient::Attribute::DPI_Y, _))
+            .WillOnce(DoAll(SetArgPointee<3>(DEFAULT_DPI), Return(Error::NONE)));
+
+    mFlinger.setupPrimaryDisplay();
+
+    Mock::VerifyAndClear(mComposer);
+}
+
+TEST_F(DisplayTransactionTest, processDisplayChangesLockedProcessesPrimaryDisplayConnected) {
+    using android::hardware::graphics::common::V1_0::ColorMode;
+
+    setupPrimaryDisplay(1920, 1080);
+
+    sp<BBinder> token = new BBinder();
+    mFlinger.mutableCurrentState().displays.add(token, {DisplayDevice::DISPLAY_PRIMARY, true});
+
+    EXPECT_CALL(*mComposer, getActiveConfig(DisplayDevice::DISPLAY_PRIMARY, _))
+            .WillOnce(DoAll(SetArgPointee<1>(0), Return(Error::NONE)));
+    EXPECT_CALL(*mComposer, getColorModes(DisplayDevice::DISPLAY_PRIMARY, _))
+            .WillOnce(DoAll(SetArgPointee<1>(std::vector<ColorMode>({ColorMode::NATIVE})),
+                            Return(Error::NONE)));
+
+    EXPECT_CALL(*mComposer, getHdrCapabilities(DisplayDevice::DISPLAY_PRIMARY, _, _, _, _))
+            .WillOnce(DoAll(SetArgPointee<1>(std::vector<Hdr>()), Return(Error::NONE)));
+
+    auto reSurface = new RE::mock::Surface();
+    EXPECT_CALL(*mRenderEngine, createSurface())
+            .WillOnce(Return(ByMove(std::unique_ptr<RE::Surface>(reSurface))));
+    EXPECT_CALL(*reSurface, setAsync(false)).Times(1);
+    EXPECT_CALL(*reSurface, setCritical(true)).Times(1);
+    EXPECT_CALL(*reSurface, setNativeWindow(_)).Times(1);
+    EXPECT_CALL(*reSurface, queryWidth()).WillOnce(Return(1920));
+    EXPECT_CALL(*reSurface, queryHeight()).WillOnce(Return(1080));
+
+    EXPECT_CALL(*mEventThread, onHotplugReceived(DisplayDevice::DISPLAY_PRIMARY, true)).Times(1);
+
+    mFlinger.processDisplayChangesLocked();
+
+    ASSERT_TRUE(mFlinger.mutableDisplays().indexOfKey(token) >= 0);
+
+    const auto& device = mFlinger.mutableDisplays().valueFor(token);
+    ASSERT_TRUE(device.get());
+    EXPECT_TRUE(device->isSecure());
+    EXPECT_TRUE(device->isPrimary());
+
+    ssize_t i = mFlinger.mutableDrawingState().displays.indexOfKey(token);
+    ASSERT_GE(0, i);
+    const auto& draw = mFlinger.mutableDrawingState().displays[i];
+    EXPECT_EQ(DisplayDevice::DISPLAY_PRIMARY, draw.type);
+
+    EXPECT_CALL(*mComposer, setVsyncEnabled(0, IComposerClient::Vsync::DISABLE))
+            .WillOnce(Return(Error::NONE));
 }
 
 } // namespace
diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
index 4aa59a5..e55d778 100644
--- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
+++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
@@ -21,16 +21,38 @@
 
 namespace android {
 
+class EventThread;
+
+namespace RE {
+class RenderEngine;
+}
+
+namespace Hwc2 {
+class Composer;
+}
+
 class TestableSurfaceFlinger {
 public:
     // Extend this as needed for accessing SurfaceFlinger private (and public)
     // functions.
 
+    void setupRenderEngine(std::unique_ptr<RE::RenderEngine> renderEngine) {
+        mFlinger->getBE().mRenderEngine = std::move(renderEngine);
+    }
+
+    void setupComposer(std::unique_ptr<Hwc2::Composer> composer) {
+        mFlinger->getBE().mHwc.reset(new HWComposer(std::move(composer)));
+    }
+
+    void setupPrimaryDisplay() {
+        mFlinger->getBE().mHwc->mHwcDevice->onHotplug(0, HWC2::Connection::Connected);
+        mFlinger->getBE().mHwc->onHotplug(0, DisplayDevice::DISPLAY_PRIMARY,
+                                          HWC2::Connection::Connected);
+    }
+
     /* ------------------------------------------------------------------------
      * Forwarding for functions being tested
      */
-    auto getDefaultDisplayDeviceLocked() const { return mFlinger->getDefaultDisplayDeviceLocked(); }
-
     auto processDisplayChangesLocked() { return mFlinger->processDisplayChangesLocked(); }
 
     /* ------------------------------------------------------------------------
@@ -38,6 +60,22 @@
      * post-conditions.
      */
     auto& mutableBuiltinDisplays() { return mFlinger->mBuiltinDisplays; }
+    auto& mutableDisplays() { return mFlinger->mDisplays; }
+    auto& mutableCurrentState() { return mFlinger->mCurrentState; }
+    auto& mutableDrawingState() { return mFlinger->mDrawingState; }
+    auto& mutableEventThread() { return mFlinger->mEventThread; }
+    auto& mutableEventQueue() { return mFlinger->mEventQueue; }
+
+    ~TestableSurfaceFlinger() {
+        // All these pointer and container clears help ensure that GMock does
+        // not report a leaked object, since the SurfaceFlinger instance may
+        // still be referenced by something despite our best efforts to destroy
+        // it after each test is done.
+        mutableDisplays().clear();
+        mutableEventThread().reset();
+        mFlinger->getBE().mHwc.reset();
+        mFlinger->getBE().mRenderEngine.reset();
+    }
 
     sp<SurfaceFlinger> mFlinger = new SurfaceFlinger();
 };
diff --git a/services/vr/bufferhubd/buffer_hub.cpp b/services/vr/bufferhubd/buffer_hub.cpp
index cdb1f91..1eb4ef9 100644
--- a/services/vr/bufferhubd/buffer_hub.cpp
+++ b/services/vr/bufferhubd/buffer_hub.cpp
@@ -62,8 +62,6 @@
   stream << std::setw(18) << "Signaled";
   stream << " ";
   stream << std::setw(10) << "Index";
-  stream << " ";
-  stream << "Name";
   stream << std::endl;
 
   for (const auto& channel : channels) {
@@ -100,8 +98,6 @@
       stream << std::dec << std::setfill(' ');
       stream << " ";
       stream << std::setw(8) << info.index;
-      stream << " ";
-      stream << info.name;
       stream << std::endl;
     }
   }
@@ -166,9 +162,7 @@
   stream << std::right;
   stream << std::setw(6) << "Id";
   stream << " ";
-  stream << std::setw(14) << "Geometry";
-  stream << " ";
-  stream << "Name";
+  stream << std::setw(14) << "Info";
   stream << std::endl;
 
   for (const auto& channel : channels) {
@@ -216,16 +210,6 @@
           *this, &BufferHubService::OnCreateBuffer, message);
       return {};
 
-    case BufferHubRPC::CreatePersistentBuffer::Opcode:
-      DispatchRemoteMethod<BufferHubRPC::CreatePersistentBuffer>(
-          *this, &BufferHubService::OnCreatePersistentBuffer, message);
-      return {};
-
-    case BufferHubRPC::GetPersistentBuffer::Opcode:
-      DispatchRemoteMethod<BufferHubRPC::GetPersistentBuffer>(
-          *this, &BufferHubService::OnGetPersistentBuffer, message);
-      return {};
-
     case BufferHubRPC::CreateProducerQueue::Opcode:
       DispatchRemoteMethod<BufferHubRPC::CreateProducerQueue>(
           *this, &BufferHubService::OnCreateProducerQueue, message);
@@ -236,12 +220,6 @@
   }
 }
 
-void BufferHubService::OnChannelClose(Message&,
-                                      const std::shared_ptr<Channel>& channel) {
-  if (auto buffer = std::static_pointer_cast<BufferHubChannel>(channel))
-    buffer->Detach();
-}
-
 Status<void> BufferHubService::OnCreateBuffer(Message& message, uint32_t width,
                                               uint32_t height, uint32_t format,
                                               uint64_t usage,
@@ -273,117 +251,6 @@
   }
 }
 
-Status<void> BufferHubService::OnCreatePersistentBuffer(
-    Message& message, const std::string& name, int user_id, int group_id,
-    uint32_t width, uint32_t height, uint32_t format, uint64_t usage,
-    size_t meta_size_bytes) {
-  const uint32_t kDefaultLayerCount = 1;
-  const int channel_id = message.GetChannelId();
-  ALOGD_IF(TRACE,
-           "BufferHubService::OnCreatePersistentBuffer: channel_id=%d name=%s "
-           "user_id=%d group_id=%d width=%u height=%u format=%u "
-           "usage=%" PRIx64 " meta_size_bytes=%zu",
-           channel_id, name.c_str(), user_id, group_id, width, height, format,
-           usage, meta_size_bytes);
-
-  // See if this channel is already attached to a buffer.
-  if (const auto channel = message.GetChannel<BufferHubChannel>()) {
-    ALOGE(
-        "BufferHubService::OnCreatePersistentBuffer: Channel already attached "
-        "to buffer: channel_id=%d buffer_id=%d",
-        channel_id, channel->buffer_id());
-    return ErrorStatus(EALREADY);
-  }
-
-  const int euid = message.GetEffectiveUserId();
-  const int egid = message.GetEffectiveGroupId();
-
-  if (auto buffer = GetNamedBuffer(name)) {
-    if (!buffer->CheckAccess(euid, egid)) {
-      ALOGE(
-          "BufferHubService::OnCreatePersistentBuffer: Requesting process does "
-          "not have permission to access named buffer: name=%s euid=%d egid=%d",
-          name.c_str(), euid, euid);
-      return ErrorStatus(EPERM);
-    } else if (!buffer->CheckParameters(width, height, kDefaultLayerCount,
-                                        format, usage, meta_size_bytes)) {
-      ALOGE(
-          "BufferHubService::OnCreatePersistentBuffer: Requested an existing "
-          "buffer with different parameters: name=%s",
-          name.c_str());
-      return ErrorStatus(EINVAL);
-    } else if (!buffer->IsDetached()) {
-      ALOGE(
-          "BufferHubService::OnCreatePersistentBuffer: Requesting a persistent "
-          "buffer that is already attached to a channel: name=%s",
-          name.c_str());
-      return ErrorStatus(EINVAL);
-    } else {
-      buffer->Attach(channel_id);
-      message.SetChannel(buffer);
-      return {};
-    }
-  } else {
-    auto status = ProducerChannel::Create(this, channel_id, width, height,
-                                          kDefaultLayerCount, format, usage,
-                                          meta_size_bytes);
-    if (!status) {
-      ALOGE("BufferHubService::OnCreateBuffer: Failed to create producer!!");
-      return status.error_status();
-    }
-    auto persistent_buffer = status.take();
-    auto make_persistent_status = persistent_buffer->OnProducerMakePersistent(
-        message, name, user_id, group_id);
-    if (make_persistent_status)
-      message.SetChannel(persistent_buffer);
-    return make_persistent_status;
-  }
-}
-
-Status<void> BufferHubService::OnGetPersistentBuffer(Message& message,
-                                                     const std::string& name) {
-  const int channel_id = message.GetChannelId();
-  ALOGD_IF(TRACE,
-           "BufferHubService::OnGetPersistentBuffer: channel_id=%d name=%s",
-           channel_id, name.c_str());
-
-  // See if this channel is already attached to a buffer.
-  if (const auto channel = message.GetChannel<BufferHubChannel>()) {
-    ALOGE(
-        "BufferHubService::OnGetPersistentBuffer: Channel already attached to "
-        "buffer: channel_id=%d buffer_id=%d",
-        channel_id, channel->buffer_id());
-    return ErrorStatus(EALREADY);
-  }
-
-  const int euid = message.GetEffectiveUserId();
-  const int egid = message.GetEffectiveGroupId();
-
-  if (auto buffer = GetNamedBuffer(name)) {
-    if (!buffer->CheckAccess(euid, egid)) {
-      ALOGE(
-          "BufferHubService::OnGetPersistentBuffer: Requesting process does "
-          "not have permission to access named buffer: name=%s euid=%d egid=%d",
-          name.c_str(), euid, egid);
-      return ErrorStatus(EPERM);
-    } else if (!buffer->IsDetached()) {
-      ALOGE(
-          "BufferHubService::OnGetPersistentBuffer: Requesting a persistent "
-          "buffer that is already attached to a channel: name=%s",
-          name.c_str());
-      return ErrorStatus(EINVAL);
-    } else {
-      buffer->Attach(channel_id);
-      message.SetChannel(buffer);
-      return {};
-    }
-  } else {
-    ALOGE("BufferHubService::OnGetPersistentBuffer: Buffer \"%s\" not found!",
-          name.c_str());
-    return ErrorStatus(ENOENT);
-  }
-}
-
 Status<QueueInfo> BufferHubService::OnCreateProducerQueue(
     pdx::Message& message, const ProducerQueueConfig& producer_config,
     const UsagePolicy& usage_policy) {
@@ -410,52 +277,17 @@
   }
 }
 
-bool BufferHubService::AddNamedBuffer(
-    const std::string& name, const std::shared_ptr<ProducerChannel>& buffer) {
-  auto search = named_buffers_.find(name);
-  if (search == named_buffers_.end()) {
-    named_buffers_.emplace(name, buffer);
-    return true;
-  } else {
-    return false;
-  }
-}
-
-std::shared_ptr<ProducerChannel> BufferHubService::GetNamedBuffer(
-    const std::string& name) {
-  auto search = named_buffers_.find(name);
-  if (search != named_buffers_.end())
-    return search->second;
-  else
-    return nullptr;
-}
-
-bool BufferHubService::RemoveNamedBuffer(const ProducerChannel& buffer) {
-  for (auto it = named_buffers_.begin(); it != named_buffers_.end();) {
-    if (it->second.get() == &buffer) {
-      named_buffers_.erase(it);
-      return true;
-    }
-    ++it;
-  }
-  return false;
-}
-
 void BufferHubChannel::SignalAvailable() {
   ATRACE_NAME("BufferHubChannel::SignalAvailable");
   ALOGD_IF(TRACE,
            "BufferHubChannel::SignalAvailable: channel_id=%d buffer_id=%d",
            channel_id(), buffer_id());
-  if (!IsDetached()) {
-    signaled_ = true;
-    const auto status = service_->ModifyChannelEvents(channel_id_, 0, POLLIN);
-    ALOGE_IF(!status,
-             "BufferHubChannel::SignalAvailable: failed to signal availability "
-             "channel_id=%d: %s",
-             channel_id_, status.GetErrorMessage().c_str());
-  } else {
-    ALOGD_IF(TRACE, "BufferHubChannel::SignalAvailable: detached buffer.");
-  }
+  signaled_ = true;
+  const auto status = service_->ModifyChannelEvents(channel_id_, 0, POLLIN);
+  ALOGE_IF(!status,
+           "BufferHubChannel::SignalAvailable: failed to signal availability "
+           "channel_id=%d: %s",
+           channel_id_, status.GetErrorMessage().c_str());
 }
 
 void BufferHubChannel::ClearAvailable() {
@@ -463,31 +295,23 @@
   ALOGD_IF(TRACE,
            "BufferHubChannel::ClearAvailable: channel_id=%d buffer_id=%d",
            channel_id(), buffer_id());
-  if (!IsDetached()) {
-    signaled_ = false;
-    const auto status = service_->ModifyChannelEvents(channel_id_, POLLIN, 0);
-    ALOGE_IF(!status,
-             "BufferHubChannel::ClearAvailable: failed to clear availability "
-             "channel_id=%d: %s",
-             channel_id_, status.GetErrorMessage().c_str());
-  } else {
-    ALOGD_IF(TRACE, "BufferHubChannel::ClearAvailable: detached buffer.");
-  }
+  signaled_ = false;
+  const auto status = service_->ModifyChannelEvents(channel_id_, POLLIN, 0);
+  ALOGE_IF(!status,
+           "BufferHubChannel::ClearAvailable: failed to clear availability "
+           "channel_id=%d: %s",
+           channel_id_, status.GetErrorMessage().c_str());
 }
 
 void BufferHubChannel::Hangup() {
   ATRACE_NAME("BufferHubChannel::Hangup");
   ALOGD_IF(TRACE, "BufferHubChannel::Hangup: channel_id=%d buffer_id=%d",
            channel_id(), buffer_id());
-  if (!IsDetached()) {
-    const auto status = service_->ModifyChannelEvents(channel_id_, 0, POLLHUP);
-    ALOGE_IF(
-        !status,
-        "BufferHubChannel::Hangup: failed to signal hangup channel_id=%d: %s",
-        channel_id_, status.GetErrorMessage().c_str());
-  } else {
-    ALOGD_IF(TRACE, "BufferHubChannel::Hangup: detached buffer.");
-  }
+  const auto status = service_->ModifyChannelEvents(channel_id_, 0, POLLHUP);
+  ALOGE_IF(
+      !status,
+      "BufferHubChannel::Hangup: failed to signal hangup channel_id=%d: %s",
+      channel_id_, status.GetErrorMessage().c_str());
 }
 
 }  // namespace dvr
diff --git a/services/vr/bufferhubd/buffer_hub.h b/services/vr/bufferhubd/buffer_hub.h
index 270ac95..b487b0b 100644
--- a/services/vr/bufferhubd/buffer_hub.h
+++ b/services/vr/bufferhubd/buffer_hub.h
@@ -27,8 +27,6 @@
     kConsumerQueueType,
   };
 
-  enum : int { kDetachedId = -1 };
-
   BufferHubChannel(BufferHubService* service, int buffer_id, int channel_id,
                    ChannelType channel_type)
       : service_(service),
@@ -57,7 +55,6 @@
     uint64_t state = 0;
     uint64_t signaled_mask = 0;
     uint64_t index = 0;
-    std::string name;
 
     // Data filed for producer queue.
     size_t capacity = 0;
@@ -66,7 +63,7 @@
     BufferInfo(int id, size_t consumer_count, uint32_t width, uint32_t height,
                uint32_t layer_count, uint32_t format, uint64_t usage,
                size_t pending_count, uint64_t state, uint64_t signaled_mask,
-               uint64_t index, const std::string& name)
+               uint64_t index)
         : id(id),
           type(kProducerType),
           consumer_count(consumer_count),
@@ -78,8 +75,7 @@
           pending_count(pending_count),
           state(state),
           signaled_mask(signaled_mask),
-          index(index),
-          name(name) {}
+          index(index) {}
 
     BufferInfo(int id, size_t consumer_count, size_t capacity,
                const UsagePolicy& usage_policy)
@@ -109,19 +105,9 @@
   int buffer_id() const { return buffer_id_; }
 
   int channel_id() const { return channel_id_; }
-  bool IsDetached() const { return channel_id_ == kDetachedId; }
 
   bool signaled() const { return signaled_; }
 
-  void Detach() {
-    if (channel_type_ == kProducerType)
-      channel_id_ = kDetachedId;
-  }
-  void Attach(int channel_id) {
-    if (channel_type_ == kProducerType && channel_id_ == kDetachedId)
-      channel_id_ = channel_id;
-  }
-
  private:
   BufferHubService* service_;
 
@@ -132,8 +118,7 @@
   // general because channel ids are not used for any lookup in this service.
   int buffer_id_;
 
-  // The channel id of the buffer. This may change for a persistent producer
-  // buffer if it is detached and re-attached to another channel.
+  // The channel id of the buffer.
   int channel_id_;
 
   bool signaled_;
@@ -152,34 +137,15 @@
   pdx::Status<void> HandleMessage(pdx::Message& message) override;
   void HandleImpulse(pdx::Message& message) override;
 
-  void OnChannelClose(pdx::Message& message,
-                      const std::shared_ptr<pdx::Channel>& channel) override;
-
   bool IsInitialized() const override;
   std::string DumpState(size_t max_length) override;
 
-  bool AddNamedBuffer(const std::string& name,
-                      const std::shared_ptr<ProducerChannel>& buffer);
-  std::shared_ptr<ProducerChannel> GetNamedBuffer(const std::string& name);
-  bool RemoveNamedBuffer(const ProducerChannel& buffer);
-
  private:
   friend BASE;
 
-  std::unordered_map<std::string, std::shared_ptr<ProducerChannel>>
-      named_buffers_;
-
   pdx::Status<void> OnCreateBuffer(pdx::Message& message, uint32_t width,
                                    uint32_t height, uint32_t format,
                                    uint64_t usage, size_t meta_size_bytes);
-  pdx::Status<void> OnCreatePersistentBuffer(pdx::Message& message,
-                                             const std::string& name,
-                                             int user_id, int group_id,
-                                             uint32_t width, uint32_t height,
-                                             uint32_t format, uint64_t usage,
-                                             size_t meta_size_bytes);
-  pdx::Status<void> OnGetPersistentBuffer(pdx::Message& message,
-                                          const std::string& name);
   pdx::Status<QueueInfo> OnCreateProducerQueue(
       pdx::Message& message, const ProducerQueueConfig& producer_config,
       const UsagePolicy& usage_policy);
diff --git a/services/vr/bufferhubd/producer_channel.cpp b/services/vr/bufferhubd/producer_channel.cpp
index 716db5e..8160193 100644
--- a/services/vr/bufferhubd/producer_channel.cpp
+++ b/services/vr/bufferhubd/producer_channel.cpp
@@ -145,7 +145,7 @@
   return BufferInfo(buffer_id(), consumer_channels_.size(), buffer_.width(),
                     buffer_.height(), buffer_.layer_count(), buffer_.format(),
                     buffer_.usage(), pending_consumers_, buffer_state_->load(),
-                    signaled_mask, metadata_header_->queue_index, name_);
+                    signaled_mask, metadata_header_->queue_index);
 }
 
 void ProducerChannel::HandleImpulse(Message& message) {
@@ -183,16 +183,6 @@
           *this, &ProducerChannel::OnProducerGain, message);
       return true;
 
-    case BufferHubRPC::ProducerMakePersistent::Opcode:
-      DispatchRemoteMethod<BufferHubRPC::ProducerMakePersistent>(
-          *this, &ProducerChannel::OnProducerMakePersistent, message);
-      return true;
-
-    case BufferHubRPC::ProducerRemovePersistence::Opcode:
-      DispatchRemoteMethod<BufferHubRPC::ProducerRemovePersistence>(
-          *this, &ProducerChannel::OnRemovePersistence, message);
-      return true;
-
     default:
       return false;
   }
@@ -459,50 +449,6 @@
       buffer_state_->load(), fence_state_->load());
 }
 
-Status<void> ProducerChannel::OnProducerMakePersistent(Message& message,
-                                                       const std::string& name,
-                                                       int user_id,
-                                                       int group_id) {
-  ATRACE_NAME("ProducerChannel::OnProducerMakePersistent");
-  ALOGD_IF(TRACE,
-           "ProducerChannel::OnProducerMakePersistent: buffer_id=%d name=%s "
-           "user_id=%d group_id=%d",
-           buffer_id(), name.c_str(), user_id, group_id);
-
-  if (name.empty() || (user_id < 0 && user_id != kNoCheckId) ||
-      (group_id < 0 && group_id != kNoCheckId)) {
-    return ErrorStatus(EINVAL);
-  }
-
-  // Try to add this buffer with the requested name.
-  if (service()->AddNamedBuffer(name, std::static_pointer_cast<ProducerChannel>(
-                                          shared_from_this()))) {
-    // If successful, set the requested permissions.
-
-    // A value of zero indicates that the ids from the sending process should be
-    // used.
-    if (user_id == kUseCallerId)
-      user_id = message.GetEffectiveUserId();
-    if (group_id == kUseCallerId)
-      group_id = message.GetEffectiveGroupId();
-
-    owner_user_id_ = user_id;
-    owner_group_id_ = group_id;
-    name_ = name;
-    return {};
-  } else {
-    // Otherwise a buffer with that name already exists.
-    return ErrorStatus(EALREADY);
-  }
-}
-
-Status<void> ProducerChannel::OnRemovePersistence(Message&) {
-  if (service()->RemoveNamedBuffer(*this))
-    return {};
-  else
-    return ErrorStatus(ENOENT);
-}
-
 void ProducerChannel::AddConsumer(ConsumerChannel* channel) {
   consumer_channels_.push_back(channel);
 }
@@ -546,16 +492,6 @@
   }
 }
 
-// Returns true if either the user or group ids match the owning ids or both
-// owning ids are not set, in which case access control does not apply.
-bool ProducerChannel::CheckAccess(int euid, int egid) {
-  const bool no_check =
-      owner_user_id_ == kNoCheckId && owner_group_id_ == kNoCheckId;
-  const bool euid_check = euid == owner_user_id_ || euid == kRootId;
-  const bool egid_check = egid == owner_group_id_ || egid == kRootId;
-  return no_check || euid_check || egid_check;
-}
-
 // Returns true if the given parameters match the underlying buffer parameters.
 bool ProducerChannel::CheckParameters(uint32_t width, uint32_t height,
                                       uint32_t layer_count, uint32_t format,
diff --git a/services/vr/bufferhubd/producer_channel.h b/services/vr/bufferhubd/producer_channel.h
index e280f4d..c5dbf0e 100644
--- a/services/vr/bufferhubd/producer_channel.h
+++ b/services/vr/bufferhubd/producer_channel.h
@@ -57,16 +57,10 @@
   void AddConsumer(ConsumerChannel* channel);
   void RemoveConsumer(ConsumerChannel* channel);
 
-  bool CheckAccess(int euid, int egid);
   bool CheckParameters(uint32_t width, uint32_t height, uint32_t layer_count,
                        uint32_t format, uint64_t usage,
                        size_t user_metadata_size);
 
-  pdx::Status<void> OnProducerMakePersistent(Message& message,
-                                             const std::string& name,
-                                             int user_id, int group_id);
-  pdx::Status<void> OnRemovePersistence(Message& message);
-
  private:
   std::vector<ConsumerChannel*> consumer_channels_;
   // This counts the number of consumers left to process this buffer. If this is
@@ -98,16 +92,6 @@
   pdx::LocalHandle release_fence_fd_;
   pdx::LocalHandle dummy_fence_fd_;
 
-  static constexpr int kNoCheckId = -1;
-  static constexpr int kUseCallerId = 0;
-  static constexpr int kRootId = 0;
-
-  // User and group id to check when obtaining a persistent buffer.
-  int owner_user_id_ = kNoCheckId;
-  int owner_group_id_ = kNoCheckId;
-
-  std::string name_;
-
   ProducerChannel(BufferHubService* service, int channel, uint32_t width,
                   uint32_t height, uint32_t layer_count, uint32_t format,
                   uint64_t usage, size_t user_metadata_size, int* error);
diff --git a/services/vr/hardware_composer/Android.bp b/services/vr/hardware_composer/Android.bp
index caf9049..90edf69 100644
--- a/services/vr/hardware_composer/Android.bp
+++ b/services/vr/hardware_composer/Android.bp
@@ -8,7 +8,6 @@
 
   static_libs: [
     "libbroadcastring",
-    "libhwcomposer-client",
     "libdisplay",
   ],
 
@@ -33,10 +32,11 @@
 
   header_libs: [
     "android.hardware.graphics.composer@2.1-command-buffer",
+    "android.hardware.graphics.composer@2.1-hal",
   ],
 
-  export_static_lib_headers: [
-    "libhwcomposer-client",
+  export_header_lib_headers: [
+    "android.hardware.graphics.composer@2.1-hal",
   ],
 
   export_shared_lib_headers: [
diff --git a/services/vr/hardware_composer/impl/vr_composer_client.cpp b/services/vr/hardware_composer/impl/vr_composer_client.cpp
index abe571a..4b90031 100644
--- a/services/vr/hardware_composer/impl/vr_composer_client.cpp
+++ b/services/vr/hardware_composer/impl/vr_composer_client.cpp
@@ -24,84 +24,52 @@
 
 namespace android {
 namespace dvr {
-namespace {
 
 using android::hardware::graphics::common::V1_0::PixelFormat;
 using android::frameworks::vr::composer::V1_0::IVrComposerClient;
 
-class ComposerClientImpl : public ComposerClient {
- public:
-  ComposerClientImpl(android::dvr::VrHwc& hal);
-  virtual ~ComposerClientImpl();
-
- private:
-  class VrCommandReader : public ComposerClient::CommandReader {
-   public:
-    VrCommandReader(ComposerClientImpl& client);
-    ~VrCommandReader() override;
-
-    bool parseCommand(IComposerClient::Command command,
-                      uint16_t length) override;
-
-   private:
-    bool parseSetLayerInfo(uint16_t length);
-    bool parseSetClientTargetMetadata(uint16_t length);
-    bool parseSetLayerBufferMetadata(uint16_t length);
-
-    IVrComposerClient::BufferMetadata readBufferMetadata();
-
-    ComposerClientImpl& mVrClient;
-    android::dvr::VrHwc& mVrHal;
-
-    VrCommandReader(const VrCommandReader&) = delete;
-    void operator=(const VrCommandReader&) = delete;
-  };
-
-  std::unique_ptr<CommandReader> createCommandReader() override;
-
-  dvr::VrHwc& mVrHal;
-
-  ComposerClientImpl(const ComposerClientImpl&) = delete;
-  void operator=(const ComposerClientImpl&) = delete;
-};
-
-ComposerClientImpl::ComposerClientImpl(android::dvr::VrHwc& hal)
-    : ComposerClient(hal), mVrHal(hal) {}
-
-ComposerClientImpl::~ComposerClientImpl() {}
-
-std::unique_ptr<ComposerClient::CommandReader>
-ComposerClientImpl::createCommandReader() {
-  return std::unique_ptr<CommandReader>(new VrCommandReader(*this));
+VrComposerClient::VrComposerClient(dvr::VrHwc& hal)
+    : ComposerClient(&hal), mVrHal(hal) {
+  if (!init()) {
+      LOG_ALWAYS_FATAL("failed to initialize VrComposerClient");
+  }
 }
 
-ComposerClientImpl::VrCommandReader::VrCommandReader(ComposerClientImpl& client)
-    : CommandReader(client), mVrClient(client), mVrHal(client.mVrHal) {}
+VrComposerClient::~VrComposerClient() {}
 
-ComposerClientImpl::VrCommandReader::~VrCommandReader() {}
+std::unique_ptr<ComposerCommandEngine>
+VrComposerClient::createCommandEngine() {
+  return std::unique_ptr<VrCommandEngine>(new VrCommandEngine(*this));
+}
 
-bool ComposerClientImpl::VrCommandReader::parseCommand(
+VrComposerClient::VrCommandEngine::VrCommandEngine(VrComposerClient& client)
+    : ComposerCommandEngine(client.mHal, client.mResources.get()), mVrClient(client),
+      mVrHal(client.mVrHal) {}
+
+VrComposerClient::VrCommandEngine::~VrCommandEngine() {}
+
+bool VrComposerClient::VrCommandEngine::executeCommand(
     IComposerClient::Command command, uint16_t length) {
   IVrComposerClient::VrCommand vrCommand =
       static_cast<IVrComposerClient::VrCommand>(command);
   switch (vrCommand) {
     case IVrComposerClient::VrCommand::SET_LAYER_INFO:
-      return parseSetLayerInfo(length);
+      return executeSetLayerInfo(length);
     case IVrComposerClient::VrCommand::SET_CLIENT_TARGET_METADATA:
-      return parseSetClientTargetMetadata(length);
+      return executeSetClientTargetMetadata(length);
     case IVrComposerClient::VrCommand::SET_LAYER_BUFFER_METADATA:
-      return parseSetLayerBufferMetadata(length);
+      return executeSetLayerBufferMetadata(length);
     default:
-      return CommandReader::parseCommand(command, length);
+      return ComposerCommandEngine::executeCommand(command, length);
   }
 }
 
-bool ComposerClientImpl::VrCommandReader::parseSetLayerInfo(uint16_t length) {
+bool VrComposerClient::VrCommandEngine::executeSetLayerInfo(uint16_t length) {
   if (length != 2) {
     return false;
   }
 
-  auto err = mVrHal.setLayerInfo(mDisplay, mLayer, read(), read());
+  auto err = mVrHal.setLayerInfo(mCurrentDisplay, mCurrentLayer, read(), read());
   if (err != Error::NONE) {
     mWriter.setError(getCommandLoc(), err);
   }
@@ -109,24 +77,24 @@
   return true;
 }
 
-bool ComposerClientImpl::VrCommandReader::parseSetClientTargetMetadata(
+bool VrComposerClient::VrCommandEngine::executeSetClientTargetMetadata(
     uint16_t length) {
   if (length != 7)
     return false;
 
-  auto err = mVrHal.setClientTargetMetadata(mDisplay, readBufferMetadata());
+  auto err = mVrHal.setClientTargetMetadata(mCurrentDisplay, readBufferMetadata());
   if (err != Error::NONE)
     mWriter.setError(getCommandLoc(), err);
 
   return true;
 }
 
-bool ComposerClientImpl::VrCommandReader::parseSetLayerBufferMetadata(
+bool VrComposerClient::VrCommandEngine::executeSetLayerBufferMetadata(
     uint16_t length) {
   if (length != 7)
     return false;
 
-  auto err = mVrHal.setLayerBufferMetadata(mDisplay, mLayer,
+  auto err = mVrHal.setLayerBufferMetadata(mCurrentDisplay, mCurrentLayer,
                                            readBufferMetadata());
   if (err != Error::NONE)
     mWriter.setError(getCommandLoc(), err);
@@ -135,7 +103,7 @@
 }
 
 IVrComposerClient::BufferMetadata
-ComposerClientImpl::VrCommandReader::readBufferMetadata() {
+VrComposerClient::VrCommandEngine::readBufferMetadata() {
   IVrComposerClient::BufferMetadata metadata = {
     .width = read(),
     .height = read(),
@@ -147,136 +115,5 @@
   return metadata;
 }
 
-}  // namespace
-
-VrComposerClient::VrComposerClient(dvr::VrHwc& hal)
-    : client_(new ComposerClientImpl(hal)) {
-  client_->initialize();
-}
-
-VrComposerClient::~VrComposerClient() {}
-
-void VrComposerClient::onHotplug(Display display,
-    IComposerCallback::Connection connected) {
-  client_->onHotplug(display, connected);
-}
-
-void VrComposerClient::onRefresh(Display display) {
-  client_->onRefresh(display);
-}
-
-Return<void> VrComposerClient::registerCallback(
-    const sp<IComposerCallback>& callback) {
-  return client_->registerCallback(callback);
-}
-
-Return<uint32_t> VrComposerClient::getMaxVirtualDisplayCount() {
-  return client_->getMaxVirtualDisplayCount();
-}
-
-Return<void> VrComposerClient::createVirtualDisplay(uint32_t width,
-    uint32_t height, PixelFormat formatHint, uint32_t outputBufferSlotCount,
-    createVirtualDisplay_cb hidl_cb) {
-  return client_->createVirtualDisplay(
-      width, height, formatHint, outputBufferSlotCount, hidl_cb);
-}
-
-Return<Error> VrComposerClient::destroyVirtualDisplay(Display display) {
-  return client_->destroyVirtualDisplay(display);
-}
-
-Return<void> VrComposerClient::createLayer(Display display,
-    uint32_t bufferSlotCount, createLayer_cb hidl_cb) {
-  return client_->createLayer(display, bufferSlotCount, hidl_cb);
-}
-
-Return<Error> VrComposerClient::destroyLayer(Display display, Layer layer) {
-  return client_->destroyLayer(display, layer);
-}
-
-Return<void> VrComposerClient::getActiveConfig(Display display,
-    getActiveConfig_cb hidl_cb) {
-  return client_->getActiveConfig(display, hidl_cb);
-}
-
-Return<Error> VrComposerClient::getClientTargetSupport(Display display,
-    uint32_t width, uint32_t height, PixelFormat format, Dataspace dataspace) {
-  return client_->getClientTargetSupport(display, width, height, format,
-                                         dataspace);
-}
-
-Return<void> VrComposerClient::getColorModes(Display display,
-    getColorModes_cb hidl_cb) {
-  return client_->getColorModes(display, hidl_cb);
-}
-
-Return<void> VrComposerClient::getDisplayAttribute(Display display,
-    Config config, Attribute attribute, getDisplayAttribute_cb hidl_cb) {
-  return client_->getDisplayAttribute(display, config, attribute, hidl_cb);
-}
-
-Return<void> VrComposerClient::getDisplayConfigs(Display display,
-    getDisplayConfigs_cb hidl_cb) {
-  return client_->getDisplayConfigs(display, hidl_cb);
-}
-
-Return<void> VrComposerClient::getDisplayName(Display display,
-    getDisplayName_cb hidl_cb) {
-  return client_->getDisplayName(display, hidl_cb);
-}
-
-Return<void> VrComposerClient::getDisplayType(Display display,
-    getDisplayType_cb hidl_cb) {
-  return client_->getDisplayType(display, hidl_cb);
-}
-
-Return<void> VrComposerClient::getDozeSupport(
-    Display display, getDozeSupport_cb hidl_cb) {
-  return client_->getDozeSupport(display, hidl_cb);
-}
-
-Return<void> VrComposerClient::getHdrCapabilities(
-    Display display, getHdrCapabilities_cb hidl_cb) {
-  return client_->getHdrCapabilities(display, hidl_cb);
-}
-
-Return<Error> VrComposerClient::setActiveConfig(Display display,
-    Config config) {
-  return client_->setActiveConfig(display, config);
-}
-
-Return<Error> VrComposerClient::setColorMode(Display display, ColorMode mode) {
-  return client_->setColorMode(display, mode);
-}
-
-Return<Error> VrComposerClient::setPowerMode(Display display, PowerMode mode) {
-  return client_->setPowerMode(display, mode);
-}
-
-Return<Error> VrComposerClient::setVsyncEnabled(Display display,
-    Vsync enabled) {
-  return client_->setVsyncEnabled(display, enabled);
-}
-
-Return<Error> VrComposerClient::setClientTargetSlotCount(
-    Display display, uint32_t clientTargetSlotCount) {
-  return client_->setClientTargetSlotCount(display, clientTargetSlotCount);
-}
-
-Return<Error> VrComposerClient::setInputCommandQueue(
-    const hardware::MQDescriptorSync<uint32_t>& descriptor) {
-  return client_->setInputCommandQueue(descriptor);
-}
-
-Return<void> VrComposerClient::getOutputCommandQueue(
-    getOutputCommandQueue_cb hidl_cb) {
-  return client_->getOutputCommandQueue(hidl_cb);
-}
-
-Return<void> VrComposerClient::executeCommands(uint32_t inLength,
-    const hidl_vec<hidl_handle>& inHandles, executeCommands_cb hidl_cb) {
-  return client_->executeCommands(inLength, inHandles, hidl_cb);
-}
-
 }  // namespace dvr
 }  // namespace android
diff --git a/services/vr/hardware_composer/impl/vr_composer_client.h b/services/vr/hardware_composer/impl/vr_composer_client.h
index 63ee86f..76b1c4f 100644
--- a/services/vr/hardware_composer/impl/vr_composer_client.h
+++ b/services/vr/hardware_composer/impl/vr_composer_client.h
@@ -17,75 +17,55 @@
 #ifndef ANDROID_DVR_HARDWARE_COMPOSER_IMPL_VR_COMPOSER_CLIENT_H
 #define ANDROID_DVR_HARDWARE_COMPOSER_IMPL_VR_COMPOSER_CLIENT_H
 
-#include <ComposerClient.h>
 #include <android/frameworks/vr/composer/1.0/IVrComposerClient.h>
 #include <composer-command-buffer/2.1/ComposerCommandBuffer.h>
+#include <composer-hal/2.1/ComposerClient.h>
+#include <composer-hal/2.1/ComposerCommandEngine.h>
 
 namespace android {
 namespace dvr {
 
 class VrHwc;
 
-using hardware::graphics::common::V1_0::PixelFormat;
-using hardware::graphics::composer::V2_1::implementation::ComposerClient;
+using hardware::graphics::composer::V2_1::hal::ComposerCommandEngine;
+using hardware::graphics::composer::V2_1::hal::ComposerHal;
+using hardware::graphics::composer::V2_1::hal::detail::ComposerClientImpl;
 
-class VrComposerClient : public IVrComposerClient {
+using ComposerClient = ComposerClientImpl<IVrComposerClient, ComposerHal>;
+
+class VrComposerClient : public ComposerClient {
  public:
   VrComposerClient(android::dvr::VrHwc& hal);
   virtual ~VrComposerClient();
 
-  void onHotplug(Display display, IComposerCallback::Connection connected);
-  void onRefresh(Display display);
-
-  // IComposerClient
-  Return<void> registerCallback(const sp<IComposerCallback>& callback) override;
-  Return<uint32_t> getMaxVirtualDisplayCount() override;
-  Return<void> createVirtualDisplay(
-      uint32_t width, uint32_t height, PixelFormat formatHint,
-      uint32_t outputBufferSlotCount, createVirtualDisplay_cb hidl_cb) override;
-  Return<Error> destroyVirtualDisplay(Display display) override;
-  Return<void> createLayer(Display display, uint32_t bufferSlotCount,
-                           createLayer_cb hidl_cb) override;
-  Return<Error> destroyLayer(Display display, Layer layer) override;
-  Return<void> getActiveConfig(Display display,
-                               getActiveConfig_cb hidl_cb) override;
-  Return<Error> getClientTargetSupport(
-      Display display, uint32_t width, uint32_t height, PixelFormat format,
-      Dataspace dataspace) override;
-  Return<void> getColorModes(Display display,
-                             getColorModes_cb hidl_cb) override;
-  Return<void> getDisplayAttribute(
-      Display display, Config config, Attribute attribute,
-      getDisplayAttribute_cb hidl_cb) override;
-  Return<void> getDisplayConfigs(Display display,
-                                 getDisplayConfigs_cb hidl_cb) override;
-  Return<void> getDisplayName(Display display,
-                              getDisplayName_cb hidl_cb) override;
-  Return<void> getDisplayType(Display display,
-                              getDisplayType_cb hidl_cb) override;
-  Return<void> getDozeSupport(Display display,
-                              getDozeSupport_cb hidl_cb) override;
-  Return<void> getHdrCapabilities(Display display,
-                                  getHdrCapabilities_cb hidl_cb) override;
-  Return<Error> setActiveConfig(Display display, Config config) override;
-  Return<Error> setColorMode(Display display, ColorMode mode) override;
-  Return<Error> setPowerMode(Display display, PowerMode mode) override;
-  Return<Error> setVsyncEnabled(Display display, Vsync enabled) override;
-  Return<Error> setClientTargetSlotCount(
-      Display display, uint32_t clientTargetSlotCount) override;
-  Return<Error> setInputCommandQueue(
-      const hardware::MQDescriptorSync<uint32_t>& descriptor) override;
-  Return<void> getOutputCommandQueue(
-      getOutputCommandQueue_cb hidl_cb) override;
-  Return<void> executeCommands(
-      uint32_t inLength, const hidl_vec<hidl_handle>& inHandles,
-      executeCommands_cb hidl_cb) override;
-
  private:
-  std::unique_ptr<ComposerClient> client_;
+  class VrCommandEngine : public ComposerCommandEngine {
+   public:
+    VrCommandEngine(VrComposerClient& client);
+    ~VrCommandEngine() override;
+
+    bool executeCommand(IComposerClient::Command command,
+                        uint16_t length) override;
+
+   private:
+    bool executeSetLayerInfo(uint16_t length);
+    bool executeSetClientTargetMetadata(uint16_t length);
+    bool executeSetLayerBufferMetadata(uint16_t length);
+
+    IVrComposerClient::BufferMetadata readBufferMetadata();
+
+    VrComposerClient& mVrClient;
+    android::dvr::VrHwc& mVrHal;
+
+    VrCommandEngine(const VrCommandEngine&) = delete;
+    void operator=(const VrCommandEngine&) = delete;
+  };
 
   VrComposerClient(const VrComposerClient&) = delete;
   void operator=(const VrComposerClient&) = delete;
+
+  std::unique_ptr<ComposerCommandEngine> createCommandEngine() override;
+  dvr::VrHwc& mVrHal;
 };
 
 } // namespace dvr
diff --git a/services/vr/hardware_composer/impl/vr_hwc.cpp b/services/vr/hardware_composer/impl/vr_hwc.cpp
index d5664d5..180e232 100644
--- a/services/vr/hardware_composer/impl/vr_hwc.cpp
+++ b/services/vr/hardware_composer/impl/vr_hwc.cpp
@@ -234,13 +234,10 @@
 
 bool VrHwc::hasCapability(hwc2_capability_t /* capability */) { return false; }
 
-void VrHwc::removeClient() {
-  std::lock_guard<std::mutex> guard(mutex_);
-  client_ = nullptr;
-}
+void VrHwc::registerEventCallback(EventCallback* callback) {
+  event_callback_ = callback;
 
-void VrHwc::enableCallback(bool enable) {
-  if (enable && client_ != nullptr) {
+  if (client_ != nullptr) {
     {
       int32_t width, height;
       GetPrimaryDisplaySize(&width, &height);
@@ -249,8 +246,8 @@
       // VR HWC and SurfaceFlinger.
       displays_[kDefaultDisplayId].reset(new HwcDisplay(width, height));
     }
-    client_.promote()->onHotplug(kDefaultDisplayId,
-                                 IComposerCallback::Connection::CONNECTED);
+    event_callback_->onHotplug(kDefaultDisplayId,
+                               IComposerCallback::Connection::CONNECTED);
   }
 }
 
@@ -857,9 +854,9 @@
 
 void VrHwc::ForceDisplaysRefresh() {
   std::lock_guard<std::mutex> guard(mutex_);
-  if (client_ != nullptr) {
+  if (event_callback_ != nullptr) {
     for (const auto& pair : displays_)
-      client_.promote()->onRefresh(pair.first);
+      event_callback_->onRefresh(pair.first);
   }
 }
 
diff --git a/services/vr/hardware_composer/impl/vr_hwc.h b/services/vr/hardware_composer/impl/vr_hwc.h
index eff721b..1c308f2 100644
--- a/services/vr/hardware_composer/impl/vr_hwc.h
+++ b/services/vr/hardware_composer/impl/vr_hwc.h
@@ -19,7 +19,7 @@
 #include <android-base/unique_fd.h>
 #include <android/frameworks/vr/composer/1.0/IVrComposerClient.h>
 #include <android/hardware/graphics/composer/2.1/IComposer.h>
-#include <ComposerBase.h>
+#include <composer-hal/2.1/ComposerHal.h>
 #include <ui/Fence.h>
 #include <ui/GraphicBuffer.h>
 #include <utils/StrongPointer.h>
@@ -46,7 +46,7 @@
 class VrComposerClient;
 
 using android::hardware::graphics::common::V1_0::PixelFormat;
-using android::hardware::graphics::composer::V2_1::implementation::ComposerBase;
+using android::hardware::graphics::composer::V2_1::hal::ComposerHal;
 
 class ComposerView {
  public:
@@ -191,7 +191,7 @@
   void operator=(const HwcDisplay&) = delete;
 };
 
-class VrHwc : public IComposer, public ComposerBase, public ComposerView {
+class VrHwc : public IComposer, public ComposerHal, public ComposerView {
  public:
   VrHwc();
   ~VrHwc() override;
@@ -204,11 +204,12 @@
       Display display, Layer layer,
       const IVrComposerClient::BufferMetadata& metadata);
 
-  // ComposerBase
+  // ComposerHal
   bool hasCapability(hwc2_capability_t capability) override;
 
-  void removeClient() override;
-  void enableCallback(bool enable) override;
+  std::string dumpDebugInfo() override { return {}; }
+  void registerEventCallback(EventCallback* callback) override;
+  void unregisterEventCallback() override {}
 
   uint32_t getMaxVirtualDisplayCount() override;
   Error createVirtualDisplay(uint32_t width, uint32_t height,
@@ -304,6 +305,7 @@
   std::unordered_map<Display, std::unique_ptr<HwcDisplay>> displays_;
   Display display_count_ = 2;
 
+  EventCallback* event_callback_ = nullptr;
   Observer* observer_ = nullptr;
 
   VrHwc(const VrHwc&) = delete;
diff --git a/vulkan/libvulkan/swapchain.cpp b/vulkan/libvulkan/swapchain.cpp
index 9fbde8c..6f3790b 100644
--- a/vulkan/libvulkan/swapchain.cpp
+++ b/vulkan/libvulkan/swapchain.cpp
@@ -573,8 +573,15 @@
     }
 
     // TODO(jessehall): Figure out what the min/max values should be.
+    int max_buffer_count;
+    err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &max_buffer_count);
+    if (err != 0) {
+        ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
+              strerror(-err), err);
+        return VK_ERROR_SURFACE_LOST_KHR;
+    }
     capabilities->minImageCount = 2;
-    capabilities->maxImageCount = 3;
+    capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
 
     capabilities->currentExtent =
         VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
@@ -744,11 +751,32 @@
 
 VKAPI_ATTR
 VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
-                                                 VkSurfaceKHR /*surface*/,
+                                                 VkSurfaceKHR surface,
                                                  uint32_t* count,
                                                  VkPresentModeKHR* modes) {
+    int err;
+    int query_value;
+    ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
+
+    err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &query_value);
+    if (err != 0 || query_value < 0) {
+        ALOGE("NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) value=%d",
+              strerror(-err), err, query_value);
+        return VK_ERROR_SURFACE_LOST_KHR;
+    }
+    uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
+
+    err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
+    if (err != 0 || query_value < 0) {
+        ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
+              strerror(-err), err, query_value);
+        return VK_ERROR_SURFACE_LOST_KHR;
+    }
+    uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
+
     android::Vector<VkPresentModeKHR> present_modes;
-    present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
+    if (min_undequeued_buffers + 1 < max_buffer_count)
+        present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
     present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
 
     VkPhysicalDevicePresentationPropertiesANDROID present_properties;