Merge "Add tracing tags to vibrator"
diff --git a/cmds/atrace/atrace.cpp b/cmds/atrace/atrace.cpp
index a87212b..058704c 100644
--- a/cmds/atrace/atrace.cpp
+++ b/cmds/atrace/atrace.cpp
@@ -94,6 +94,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, { } },
diff --git a/cmds/installd/InstalldNativeService.cpp b/cmds/installd/InstalldNativeService.cpp
index 0d50b9b..fe510a2 100644
--- a/cmds/installd/InstalldNativeService.cpp
+++ b/cmds/installd/InstalldNativeService.cpp
@@ -1906,7 +1906,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) {
     ENFORCE_UID(AID_SYSTEM);
     CHECK_ARGUMENT_UUID(uuid);
     if (packageName && *packageName != "*") {
@@ -1924,9 +1925,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();
 }
 
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..9680352 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.");
 
@@ -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/cmds/surfacereplayer/proto/Android.bp b/cmds/surfacereplayer/proto/Android.bp
index 71a5e23..7b402fe 100644
--- a/cmds/surfacereplayer/proto/Android.bp
+++ b/cmds/surfacereplayer/proto/Android.bp
@@ -7,6 +7,11 @@
         "-Wall",
         "-Werror",
     ],
+    arch: {
+        arm: {
+            instruction_set: "arm",
+        },
+    },
     proto: {
         type: "lite",
         export_proto_headers: 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/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..0722038 100644
--- a/libs/gui/SurfaceComposerClient.cpp
+++ b/libs/gui/SurfaceComposerClient.cpp
@@ -472,6 +472,17 @@
     return *this;
 }
 
+SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::destroySurface(
+        const sp<SurfaceControl>& sc) {
+    layer_state_t* s = getLayerStateLocked(sc);
+    if (!s) {
+        mStatus = BAD_INDEX;
+        return *this;
+    }
+    s->what |= layer_state_t::eDestroySurface;
+    return *this;
+}
+
 // ---------------------------------------------------------------------------
 
 DisplayState& SurfaceComposerClient::Transaction::getDisplayStateLocked(const sp<IBinder>& token) {
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..10caa76 100644
--- a/libs/gui/include/gui/SurfaceComposerClient.h
+++ b/libs/gui/include/gui/SurfaceComposerClient.h
@@ -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/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/Android.bp b/libs/vr/libbufferhub/Android.bp
index 39814cc..e6803da 100644
--- a/libs/vr/libbufferhub/Android.bp
+++ b/libs/vr/libbufferhub/Android.bp
@@ -48,6 +48,11 @@
         "-Wall",
         "-Werror",
     ],
+    arch: {
+        arm: {
+            instruction_set: "arm",
+        },
+    },
     export_include_dirs: localIncludeFiles,
     shared_libs: sharedLibraries,
     header_libs: headerLibraries,
diff --git a/libs/vr/libbufferhubqueue/Android.bp b/libs/vr/libbufferhubqueue/Android.bp
index eeec9ec..cf2c59b 100644
--- a/libs/vr/libbufferhubqueue/Android.bp
+++ b/libs/vr/libbufferhubqueue/Android.bp
@@ -53,6 +53,11 @@
         "-Wno-unused-parameter",
         "-Wno-unused-variable",
     ],
+    arch: {
+        arm: {
+            instruction_set: "arm",
+        },
+    },
     srcs: sourceFiles,
     export_include_dirs: includeFiles,
     export_static_lib_headers: staticLibraries,
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/libdisplay/Android.bp b/libs/vr/libdisplay/Android.bp
index 192fb5d..093ad92 100644
--- a/libs/vr/libdisplay/Android.bp
+++ b/libs/vr/libdisplay/Android.bp
@@ -52,6 +52,11 @@
 cc_library {
     tags: ["tests"],
     srcs: sourceFiles,
+    arch: {
+        arm: {
+            instruction_set: "arm",
+        },
+    },
     cflags: ["-DLOG_TAG=\"libdisplay\"",
         "-DTRACE=0",
         "-DATRACE_TAG=ATRACE_TAG_GRAPHICS",
diff --git a/libs/vr/libpdx/Android.bp b/libs/vr/libpdx/Android.bp
index 9b84d65..d183f71 100644
--- a/libs/vr/libpdx/Android.bp
+++ b/libs/vr/libpdx/Android.bp
@@ -8,6 +8,11 @@
         "-DLOG_TAG=\"libpdx\"",
         "-DTRACE=0",
     ],
+    arch: {
+        arm: {
+            instruction_set: "arm",
+        },
+    },
     export_include_dirs: ["private"],
     local_include_dirs: ["private"],
     srcs: [
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/libs/vr/libpdx_uds/Android.bp b/libs/vr/libpdx_uds/Android.bp
index 79cfdf6..e7cf357 100644
--- a/libs/vr/libpdx_uds/Android.bp
+++ b/libs/vr/libpdx_uds/Android.bp
@@ -19,6 +19,11 @@
         "ipc_helper.cpp",
         "service_endpoint.cpp",
     ],
+    arch: {
+        arm: {
+            instruction_set: "arm",
+        },
+    },
     static_libs: [
         "libcutils",
         "libbase",
diff --git a/libs/vr/libperformance/Android.bp b/libs/vr/libperformance/Android.bp
index 35d3dea..2eed602 100644
--- a/libs/vr/libperformance/Android.bp
+++ b/libs/vr/libperformance/Android.bp
@@ -36,6 +36,11 @@
         "-Wall",
         "-Werror",
     ],
+    arch: {
+        arm: {
+            instruction_set: "arm",
+        },
+    },
     export_include_dirs: includeFiles,
     shared_libs: sharedLibraries,
     name: "libperformance",
diff --git a/libs/vr/libvr_manager/Android.bp b/libs/vr/libvr_manager/Android.bp
index 8784877..6060c6e 100644
--- a/libs/vr/libvr_manager/Android.bp
+++ b/libs/vr/libvr_manager/Android.bp
@@ -31,6 +31,11 @@
     include_dirs: include_dirs,
     export_include_dirs: exported_include_dirs,
     cflags: ["-Wall", "-Werror", "-Wunused", "-Wunreachable-code"],
+    arch: {
+        arm: {
+            instruction_set: "arm",
+        },
+    },
     static_libs: static_libs,
     name: "libvr_manager",
 }
diff --git a/libs/vr/libvrflinger/Android.bp b/libs/vr/libvrflinger/Android.bp
index 23a9853..c762e46 100644
--- a/libs/vr/libvrflinger/Android.bp
+++ b/libs/vr/libvrflinger/Android.bp
@@ -81,6 +81,11 @@
         "-Wno-error=sign-compare", // to fix later
         "-Wno-unused-variable",
     ],
+    arch: {
+        arm: {
+            instruction_set: "arm",
+        },
+    },
     shared_libs: sharedLibraries,
     whole_static_libs: staticLibraries,
     header_libs: headerLibraries,
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/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/surfaceflinger/Android.bp b/services/surfaceflinger/Android.bp
index ae34d34..ae589ca 100644
--- a/services/surfaceflinger/Android.bp
+++ b/services/surfaceflinger/Android.bp
@@ -133,6 +133,11 @@
     srcs: [
         ":libsurfaceflinger_sources",
     ],
+    arch: {
+        arm: {
+            instruction_set: "arm",
+        },
+    },
     logtags: ["EventLog/EventLogTags.logtags"],
     include_dirs: [
         "external/vulkan-validation-layers/libs/vkjson",
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..135bfbe 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -2901,7 +2901,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 +2969,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 +3000,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 +3020,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 +3047,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 +3124,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 +3278,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..08c4a5e 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.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/layerproto/Android.bp b/services/surfaceflinger/layerproto/Android.bp
index 8eb218c..75612c0 100644
--- a/services/surfaceflinger/layerproto/Android.bp
+++ b/services/surfaceflinger/layerproto/Android.bp
@@ -9,6 +9,12 @@
         "layerstrace.proto",
     ],
 
+    arch: {
+        arm: {
+            instruction_set: "arm",
+        },
+    },
+
     shared_libs: [
         "libui",
         "libprotobuf-cpp-lite",
@@ -33,4 +39,4 @@
         "-Wno-undef",
     ],
 
-}
\ No newline at end of file
+}
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/utils/Android.bp b/services/utils/Android.bp
index 6132956..a5f7dc1 100644
--- a/services/utils/Android.bp
+++ b/services/utils/Android.bp
@@ -27,6 +27,12 @@
         "PriorityDumper.cpp",
     ],
 
+    arch: {
+        arm: {
+            instruction_set: "arm",
+        },
+    },
+
     clang: true,
     export_include_dirs: ["include"],
 }
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;