Merge "Hold onto FileHandles for glBindSharedBufferQCOM calls" into oc-dev
diff --git a/cmds/atrace/Android.bp b/cmds/atrace/Android.bp
index 69ed416..6c5869a 100644
--- a/cmds/atrace/Android.bp
+++ b/cmds/atrace/Android.bp
@@ -18,4 +18,10 @@
     ],
 
     init_rc: ["atrace.rc"],
+
+    product_variables: {
+        debuggable: {
+            init_rc: ["atrace_userdebug.rc"],
+        },
+    },
 }
diff --git a/cmds/atrace/atrace.cpp b/cmds/atrace/atrace.cpp
index 05e1615..6cfbed9 100644
--- a/cmds/atrace/atrace.cpp
+++ b/cmds/atrace/atrace.cpp
@@ -552,7 +552,13 @@
                 // ignore
                 continue;
             }
+
             sp<IBase> interface = interfaceRet;
+            if (interface == nullptr) {
+                // ignore
+                continue;
+            }
+
             auto notifyRet = interface->notifySyspropsChanged();
             if (!notifyRet.isOk()) {
                 // ignore
diff --git a/cmds/atrace/atrace_userdebug.rc b/cmds/atrace/atrace_userdebug.rc
new file mode 100644
index 0000000..5fd28e2
--- /dev/null
+++ b/cmds/atrace/atrace_userdebug.rc
@@ -0,0 +1,47 @@
+## Permissions to allow additional system-wide tracing to the kernel trace buffer.
+## The default list of permissions is set in frameworks/native/cmds/atrace/atrace.rc
+
+# Allow the shell group to enable kernel tracepoints:
+
+on post-fs
+    chown root shell /sys/kernel/debug/tracing/events/sync/enable
+    chown root shell /sys/kernel/debug/tracing/events/workqueue/enable
+    chown root shell /sys/kernel/debug/tracing/events/regulator/enable
+    chown root shell /sys/kernel/debug/tracing/events/pagecache/enable
+
+    # irq
+    chown root shell /sys/kernel/debug/tracing/events/irq/enable
+    chown root shell /sys/kernel/debug/tracing/events/ipi/enable
+
+    # disk
+    chown root shell /sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable
+    chown root shell /sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable
+    chown root shell /sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable
+    chown root shell /sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable
+    chown root shell /sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable
+    chown root shell /sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable
+    chown root shell /sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable
+    chown root shell /sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable
+    chown root shell /sys/kernel/debug/tracing/events/block/block_rq_issue/enable
+    chown root shell /sys/kernel/debug/tracing/events/block/block_rq_complete/enable
+
+    chmod 0664 /sys/kernel/debug/tracing/events/sync/enable
+    chmod 0664 /sys/kernel/debug/tracing/events/workqueue/enable
+    chmod 0664 /sys/kernel/debug/tracing/events/regulator/enable
+    chmod 0664 /sys/kernel/debug/tracing/events/pagecache/enable
+
+    # irq
+    chmod 0664 /sys/kernel/debug/tracing/events/irq/enable
+    chmod 0664 /sys/kernel/debug/tracing/events/ipi/enable
+
+    # disk
+    chmod 0664 /sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable
+    chmod 0664 /sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable
+    chmod 0664 /sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable
+    chmod 0664 /sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable
+    chmod 0664 /sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable
+    chmod 0664 /sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable
+    chmod 0664 /sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable
+    chmod 0664 /sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable
+    chmod 0664 /sys/kernel/debug/tracing/events/block/block_rq_issue/enable
+    chmod 0664 /sys/kernel/debug/tracing/events/block/block_rq_complete/enable
diff --git a/cmds/installd/dexopt.cpp b/cmds/installd/dexopt.cpp
index 63afdcd..e9d06d1 100644
--- a/cmds/installd/dexopt.cpp
+++ b/cmds/installd/dexopt.cpp
@@ -67,14 +67,6 @@
     return unique_fd(-1);
 }
 
-static const char* parse_null(const char* arg) {
-    if (strcmp(arg, "!") == 0) {
-        return nullptr;
-    } else {
-        return arg;
-    }
-}
-
 static bool clear_profile(const std::string& profile) {
     unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
     if (ufd.get() < 0) {
@@ -185,9 +177,20 @@
   return count;
 }
 
+static const char* get_location_from_path(const char* path) {
+    static constexpr char kLocationSeparator = '/';
+    const char *location = strrchr(path, kLocationSeparator);
+    if (location == NULL) {
+        return path;
+    } else {
+        // Skip the separator character.
+        return location + 1;
+    }
+}
+
 static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
         const char* input_file_name, const char* output_file_name, int swap_fd,
-        const char *instruction_set, const char* compiler_filter, bool vm_safe_mode,
+        const char* instruction_set, const char* compiler_filter, bool vm_safe_mode,
         bool debuggable, bool post_bootcomplete, int profile_fd, const char* shared_libraries) {
     static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
 
@@ -197,6 +200,9 @@
         return;
     }
 
+    // Get the relative path to the input file.
+    const char* relative_input_file_name = get_location_from_path(input_file_name);
+
     char dex2oat_Xms_flag[kPropertyValueMax];
     bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
 
@@ -287,7 +293,7 @@
     char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
 
     sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
-    sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
+    sprintf(zip_location_arg, "--zip-location=%s", relative_input_file_name);
     sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
     sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
     sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
@@ -349,8 +355,18 @@
         sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
     }
 
+    // Get the directory of the apk to pass as a base classpath directory.
+    char base_dir[arraysize("--classpath-dir=") + PKG_PATH_MAX];
+    std::string apk_dir(input_file_name);
+    unsigned long dir_index = apk_dir.rfind('/');
+    bool has_base_dir = dir_index != std::string::npos;
+    if (has_base_dir) {
+        apk_dir = apk_dir.substr(0, dir_index);
+        sprintf(base_dir, "--classpath-dir=%s", apk_dir.c_str());
+    }
 
-    ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
+
+    ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, relative_input_file_name, output_file_name);
 
     const char* argv[9  // program name, mandatory arguments and the final NULL
                      + (have_dex2oat_isa_variant ? 1 : 0)
@@ -368,6 +384,7 @@
                      + dex2oat_flags_count
                      + (profile_fd == -1 ? 0 : 1)
                      + (shared_libraries != nullptr ? 4 : 0)
+                     + (has_base_dir ? 1 : 0)
                      + (have_dex2oat_large_app_threshold ? 1 : 0)];
     int i = 0;
     argv[i++] = DEX2OAT_BIN;
@@ -432,6 +449,9 @@
         argv[i++] = RUNTIME_ARG;
         argv[i++] = shared_libraries;
     }
+    if (has_base_dir) {
+        argv[i++] = base_dir;
+    }
     // Do not add after dex2oat_flags, they should override others for debugging.
     argv[i] = NULL;
 
@@ -769,17 +789,6 @@
     exit(68);   /* only get here on exec failure */
 }
 
-static const char* get_location_from_path(const char* path) {
-    static constexpr char kLocationSeparator = '/';
-    const char *location = strrchr(path, kLocationSeparator);
-    if (location == NULL) {
-        return path;
-    } else {
-        // Skip the separator character.
-        return location + 1;
-    }
-}
-
 bool dump_profiles(int32_t uid, const std::string& pkgname, const char* code_paths) {
     std::vector<unique_fd> profile_fds;
     unique_fd reference_profile_fd;
@@ -1556,14 +1565,12 @@
             _exit(67);
         }
 
-        // Pass dex2oat the relative path to the input file.
-        const char *input_file_name = get_location_from_path(dex_path);
         run_dex2oat(input_fd.get(),
                     out_oat_fd.get(),
                     in_vdex_fd.get(),
                     out_vdex_fd.get(),
                     image_fd.get(),
-                    input_file_name,
+                    dex_path,
                     out_oat_path,
                     swap_fd.get(),
                     instruction_set,
@@ -1863,20 +1870,5 @@
     return return_value_oat && return_value_art;
 }
 
-int dexopt(const char* const params[DEXOPT_PARAM_COUNT]) {
-    return dexopt(params[0],                    // apk_path
-                  atoi(params[1]),              // uid
-                  params[2],                    // pkgname
-                  params[3],                    // instruction_set
-                  atoi(params[4]),              // dexopt_needed
-                  params[5],                    // oat_dir
-                  atoi(params[6]),              // dexopt_flags
-                  params[7],                    // compiler_filter
-                  parse_null(params[8]),        // volume_uuid
-                  parse_null(params[9]),        // shared_libraries
-                  parse_null(params[10]));       // se_info
-    static_assert(DEXOPT_PARAM_COUNT == 11U, "Unexpected dexopt param count");
-}
-
 }  // namespace installd
 }  // namespace android
diff --git a/cmds/installd/dexopt.h b/cmds/installd/dexopt.h
index 88144b7..355adb1 100644
--- a/cmds/installd/dexopt.h
+++ b/cmds/installd/dexopt.h
@@ -62,12 +62,6 @@
         int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
         const char* volume_uuid, const char* shared_libraries, const char* se_info);
 
-static constexpr size_t DEXOPT_PARAM_COUNT = 11U;
-static_assert(DEXOPT_PARAM_COUNT == 11U, "Unexpected dexopt param size");
-
-// Helper for the above, converting arguments.
-int dexopt(const char* const params[DEXOPT_PARAM_COUNT]);
-
 }  // namespace installd
 }  // namespace android
 
diff --git a/cmds/installd/otapreopt.cpp b/cmds/installd/otapreopt.cpp
index e8e6b56..ae4c797 100644
--- a/cmds/installd/otapreopt.cpp
+++ b/cmds/installd/otapreopt.cpp
@@ -16,6 +16,7 @@
 
 #include <algorithm>
 #include <inttypes.h>
+#include <limits>
 #include <random>
 #include <regex>
 #include <selinux/android.h>
@@ -40,6 +41,7 @@
 #include "dexopt.h"
 #include "file_parsing.h"
 #include "globals.h"
+#include "installd_constants.h"
 #include "installd_deps.h"  // Need to fill in requirements of commands.
 #include "otapreopt_utils.h"
 #include "system_properties.h"
@@ -145,6 +147,20 @@
 
 private:
 
+    struct Parameters {
+        const char *apk_path;
+        uid_t uid;
+        const char *pkgName;
+        const char *instruction_set;
+        int dexopt_needed;
+        const char* oat_dir;
+        int dexopt_flags;
+        const char* compiler_filter;
+        const char* volume_uuid;
+        const char* shared_libraries;
+        const char* se_info;
+    };
+
     bool ReadSystemProperties() {
         static constexpr const char* kPropertyFiles[] = {
                 "/default.prop", "/system/build.prop"
@@ -246,15 +262,23 @@
         return true;
     }
 
-    bool ReadArguments(int argc ATTRIBUTE_UNUSED, char** argv) {
-        // Expected command line:
-        //   target-slot dexopt {DEXOPT_PARAMETERS}
-        // The DEXOPT_PARAMETERS are passed on to dexopt(), so we expect DEXOPT_PARAM_COUNT
-        // of them. We store them in package_parameters_ (size checks are done when
-        // parsing the special parameters and when copying into package_parameters_.
+    bool ParseUInt(const char* in, uint32_t* out) {
+        char* end;
+        long long int result = strtoll(in, &end, 0);
+        if (in == end || *end != '\0') {
+            return false;
+        }
+        if (result < std::numeric_limits<uint32_t>::min() ||
+                std::numeric_limits<uint32_t>::max() < result) {
+            return false;
+        }
+        *out = static_cast<uint32_t>(result);
+        return true;
+    }
 
-        static_assert(DEXOPT_PARAM_COUNT == ARRAY_SIZE(package_parameters_),
-                      "Unexpected dexopt param count");
+    bool ReadArguments(int argc, char** argv) {
+        // Expected command line:
+        //   target-slot [version] dexopt {DEXOPT_PARAMETERS}
 
         const char* target_slot_arg = argv[1];
         if (target_slot_arg == nullptr) {
@@ -268,28 +292,230 @@
             return false;
         }
 
-        // Check for "dexopt" next.
+        // Check for version or "dexopt" next.
+        if (argv[2] == nullptr) {
+            LOG(ERROR) << "Missing parameters";
+            return false;
+        }
+
+        if (std::string("dexopt").compare(argv[2]) == 0) {
+            // This is version 1 (N) or pre-versioning version 2.
+            constexpr int kV2ArgCount =   1   // "otapreopt"
+                                        + 1   // slot
+                                        + 1   // "dexopt"
+                                        + 1   // apk_path
+                                        + 1   // uid
+                                        + 1   // pkg
+                                        + 1   // isa
+                                        + 1   // dexopt_needed
+                                        + 1   // oat_dir
+                                        + 1   // dexopt_flags
+                                        + 1   // filter
+                                        + 1   // volume
+                                        + 1   // libs
+                                        + 1   // seinfo
+                                        + 1;  // null
+            if (argc == kV2ArgCount) {
+                return ReadArgumentsV2(argc, argv, false);
+            } else {
+                return ReadArgumentsV1(argc, argv);
+            }
+        }
+
+        uint32_t version;
+        if (!ParseUInt(argv[2], &version)) {
+            LOG(ERROR) << "Could not parse version: " << argv[2];
+            return false;
+        }
+
+        switch (version) {
+            case 2:
+                return ReadArgumentsV2(argc, argv, true);
+
+            default:
+                LOG(ERROR) << "Unsupported version " << version;
+                return false;
+        }
+    }
+
+    bool ReadArgumentsV2(int argc ATTRIBUTE_UNUSED, char** argv, bool versioned) {
+        size_t dexopt_index = versioned ? 3 : 2;
+
+        // Check for "dexopt".
+        if (argv[dexopt_index] == nullptr) {
+            LOG(ERROR) << "Missing parameters";
+            return false;
+        }
+        if (std::string("dexopt").compare(argv[dexopt_index]) != 0) {
+            LOG(ERROR) << "Expected \"dexopt\"";
+            return false;
+        }
+
+        size_t param_index = 0;
+        for (;; ++param_index) {
+            const char* param = argv[dexopt_index + 1 + param_index];
+            if (param == nullptr) {
+                break;
+            }
+
+            switch (param_index) {
+                case 0:
+                    package_parameters_.apk_path = param;
+                    break;
+
+                case 1:
+                    package_parameters_.uid = atoi(param);
+                    break;
+
+                case 2:
+                    package_parameters_.pkgName = param;
+                    break;
+
+                case 3:
+                    package_parameters_.instruction_set = param;
+                    break;
+
+                case 4:
+                    package_parameters_.dexopt_needed = atoi(param);
+                    break;
+
+                case 5:
+                    package_parameters_.oat_dir = param;
+                    break;
+
+                case 6:
+                    package_parameters_.dexopt_flags = atoi(param);
+                    break;
+
+                case 7:
+                    package_parameters_.compiler_filter = param;
+                    break;
+
+                case 8:
+                    package_parameters_.volume_uuid = ParseNull(param);
+                    break;
+
+                case 9:
+                    package_parameters_.shared_libraries = ParseNull(param);
+                    break;
+
+                case 10:
+                    package_parameters_.se_info = ParseNull(param);
+                    break;
+
+                default:
+                    LOG(ERROR) << "Too many arguments, got " << param;
+                    return false;
+            }
+        }
+
+        if (param_index != 11) {
+            LOG(ERROR) << "Not enough parameters";
+            return false;
+        }
+
+        return true;
+    }
+
+    static int ReplaceMask(int input, int old_mask, int new_mask) {
+        return (input & old_mask) != 0 ? new_mask : 0;
+    }
+
+    bool ReadArgumentsV1(int argc ATTRIBUTE_UNUSED, char** argv) {
+        // Check for "dexopt".
         if (argv[2] == nullptr) {
             LOG(ERROR) << "Missing parameters";
             return false;
         }
         if (std::string("dexopt").compare(argv[2]) != 0) {
-            LOG(ERROR) << "Second parameter not dexopt: " << argv[2];
+            LOG(ERROR) << "Expected \"dexopt\"";
             return false;
         }
 
-        // Copy the rest into package_parameters_, but be careful about over- and underflow.
-        size_t index = 0;
-        while (index < DEXOPT_PARAM_COUNT &&
-                argv[index + 3] != nullptr) {
-            package_parameters_[index] = argv[index + 3];
-            index++;
+        size_t param_index = 0;
+        for (;; ++param_index) {
+            const char* param = argv[3 + param_index];
+            if (param == nullptr) {
+                break;
+            }
+
+            switch (param_index) {
+                case 0:
+                    package_parameters_.apk_path = param;
+                    break;
+
+                case 1:
+                    package_parameters_.uid = atoi(param);
+                    break;
+
+                case 2:
+                    package_parameters_.pkgName = param;
+                    break;
+
+                case 3:
+                    package_parameters_.instruction_set = param;
+                    break;
+
+                case 4: {
+                    // Version 1 had:
+                    //   DEXOPT_DEX2OAT_NEEDED       = 1
+                    //   DEXOPT_PATCHOAT_NEEDED      = 2
+                    //   DEXOPT_SELF_PATCHOAT_NEEDED = 3
+                    // We will simply use DEX2OAT_FROM_SCRATCH.
+                    package_parameters_.dexopt_needed = DEX2OAT_FROM_SCRATCH;
+                    break;
+                }
+
+                case 5:
+                    package_parameters_.oat_dir = param;
+                    break;
+
+                case 6: {
+                    // Version 1 had:
+                    constexpr int OLD_DEXOPT_PUBLIC         = 1 << 1;
+                    constexpr int OLD_DEXOPT_SAFEMODE       = 1 << 2;
+                    constexpr int OLD_DEXOPT_DEBUGGABLE     = 1 << 3;
+                    constexpr int OLD_DEXOPT_BOOTCOMPLETE   = 1 << 4;
+                    constexpr int OLD_DEXOPT_PROFILE_GUIDED = 1 << 5;
+                    constexpr int OLD_DEXOPT_OTA            = 1 << 6;
+                    int input = atoi(param);
+                    package_parameters_.dexopt_flags =
+                            ReplaceMask(input, OLD_DEXOPT_PUBLIC, DEXOPT_PUBLIC) |
+                            ReplaceMask(input, OLD_DEXOPT_SAFEMODE, DEXOPT_SAFEMODE) |
+                            ReplaceMask(input, OLD_DEXOPT_DEBUGGABLE, DEXOPT_DEBUGGABLE) |
+                            ReplaceMask(input, OLD_DEXOPT_BOOTCOMPLETE, DEXOPT_BOOTCOMPLETE) |
+                            ReplaceMask(input, OLD_DEXOPT_PROFILE_GUIDED, DEXOPT_PROFILE_GUIDED) |
+                            ReplaceMask(input, OLD_DEXOPT_OTA, 0);
+                    break;
+                }
+
+                case 7:
+                    package_parameters_.compiler_filter = param;
+                    break;
+
+                case 8:
+                    package_parameters_.volume_uuid = ParseNull(param);
+                    break;
+
+                case 9:
+                    package_parameters_.shared_libraries = ParseNull(param);
+                    break;
+
+                default:
+                    LOG(ERROR) << "Too many arguments, got " << param;
+                    return false;
+            }
         }
-        if (index != ARRAY_SIZE(package_parameters_) || argv[index + 3] != nullptr) {
-            LOG(ERROR) << "Wrong number of parameters";
+
+        if (param_index != 10) {
+            LOG(ERROR) << "Not enough parameters";
             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.
+        package_parameters_.se_info = nullptr;
+
         return true;
     }
 
@@ -306,11 +532,11 @@
     // Ensure that we have the right boot image. The first time any app is
     // compiled, we'll try to generate it.
     bool PrepareBootImage(bool force) const {
-        if (package_parameters_[kISAIndex] == nullptr) {
+        if (package_parameters_.instruction_set == nullptr) {
             LOG(ERROR) << "Instruction set missing.";
             return false;
         }
-        const char* isa = package_parameters_[kISAIndex];
+        const char* isa = package_parameters_.instruction_set;
 
         // Check whether the file exists where expected.
         std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
@@ -536,14 +762,12 @@
         //       (This is ugly as it's the only thing where we need to understand the contents
         //        of package_parameters_, but it beats postponing the decision or using the call-
         //        backs to do weird things.)
-        constexpr size_t kApkPathIndex = 0;
-        CHECK_GT(DEXOPT_PARAM_COUNT, kApkPathIndex);
-        CHECK(package_parameters_[kApkPathIndex] != nullptr);
-        if (StartsWith(package_parameters_[kApkPathIndex], android_root_.c_str())) {
-            const char* last_slash = strrchr(package_parameters_[kApkPathIndex], '/');
+        const char* apk_path = package_parameters_.apk_path;
+        CHECK(apk_path != nullptr);
+        if (StartsWith(apk_path, android_root_.c_str())) {
+            const char* last_slash = strrchr(apk_path, '/');
             if (last_slash != nullptr) {
-                std::string path(package_parameters_[kApkPathIndex],
-                                 last_slash - package_parameters_[kApkPathIndex] + 1);
+                std::string path(apk_path, last_slash - apk_path + 1);
                 CHECK(EndsWith(path, "/"));
                 path = path + "oat";
                 if (access(path.c_str(), F_OK) == 0) {
@@ -557,40 +781,64 @@
         // partition will not be available and fail to build. This is problematic, as
         // this tool will wipe the OTA artifact cache and try again (for robustness after
         // a failed OTA with remaining cache artifacts).
-        if (access(package_parameters_[kApkPathIndex], F_OK) != 0) {
-            LOG(WARNING) << "Skipping preopt of non-existing package "
-                         << package_parameters_[kApkPathIndex];
+        if (access(apk_path, F_OK) != 0) {
+            LOG(WARNING) << "Skipping preopt of non-existing package " << apk_path;
             return true;
         }
 
         return false;
     }
 
+    // Run dexopt with the parameters of package_parameters_.
+    int Dexopt() {
+        return dexopt(package_parameters_.apk_path,
+                      package_parameters_.uid,
+                      package_parameters_.pkgName,
+                      package_parameters_.instruction_set,
+                      package_parameters_.dexopt_needed,
+                      package_parameters_.oat_dir,
+                      package_parameters_.dexopt_flags,
+                      package_parameters_.compiler_filter,
+                      package_parameters_.volume_uuid,
+                      package_parameters_.shared_libraries,
+                      package_parameters_.se_info);
+    }
+
     int RunPreopt() {
         if (ShouldSkipPreopt()) {
             return 0;
         }
 
-        int dexopt_result = dexopt(package_parameters_);
+        int dexopt_result = Dexopt();
         if (dexopt_result == 0) {
             return 0;
         }
 
         // If the dexopt failed, we may have a stale boot image from a previous OTA run.
         // Then regenerate and retry.
-        if (WEXITSTATUS(dexopt_result) !=
+        if (WEXITSTATUS(dexopt_result) ==
                 static_cast<int>(art::dex2oat::ReturnCode::kCreateRuntime)) {
+            if (!PrepareBootImage(/* force */ true)) {
+                LOG(ERROR) << "Forced boot image creating failed. Original error return was "
+                        << dexopt_result;
+                return dexopt_result;
+            }
+
+            int dexopt_result_boot_image_retry = Dexopt();
+            if (dexopt_result_boot_image_retry == 0) {
+                return 0;
+            }
+        }
+
+        // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
+        // if possible.
+        if ((package_parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
             return dexopt_result;
         }
 
-        if (!PrepareBootImage(/* force */ true)) {
-            LOG(ERROR) << "Forced boot image creating failed. Original error return was "
-                         << dexopt_result;
-            return dexopt_result;
-        }
-
-        LOG(WARNING) << "Original dexopt failed, re-trying after boot image was regenerated.";
-        return dexopt(package_parameters_);
+        LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
+        package_parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
+        return Dexopt();
     }
 
     ////////////////////////////////////
@@ -720,7 +968,7 @@
     std::string boot_classpath_;
     std::string asec_mountpoint_;
 
-    const char* package_parameters_[DEXOPT_PARAM_COUNT];
+    Parameters package_parameters_;
 
     // Store environment values we need to set.
     std::vector<std::string> environ_;
diff --git a/cmds/installd/otapreopt_chroot.cpp b/cmds/installd/otapreopt_chroot.cpp
index cec8f68..2030997 100644
--- a/cmds/installd/otapreopt_chroot.cpp
+++ b/cmds/installd/otapreopt_chroot.cpp
@@ -27,7 +27,6 @@
 
 #include "installd_constants.h"
 #include "otapreopt_utils.h"
-#include "dexopt.h"
 
 #ifndef LOG_TAG
 #define LOG_TAG "otapreopt"
@@ -137,44 +136,18 @@
 
     // Now go on and run otapreopt.
 
-    // Incoming:  cmd + status-fd + target-slot + "dexopt" + dexopt-params + null
-    // Outgoing:  cmd             + target-slot + "dexopt" + dexopt-params + null
-    constexpr size_t kInArguments =   1                       // Binary name.
-                                    + 1                       // status file descriptor.
-                                    + 1                       // target-slot.
-                                    + 1                       // "dexopt."
-                                    + DEXOPT_PARAM_COUNT      // dexopt parameters.
-                                    + 1;                      // null termination.
-    constexpr size_t kOutArguments =   1                       // Binary name.
-                                     + 1                       // target-slot.
-                                     + 1                       // "dexopt."
-                                     + DEXOPT_PARAM_COUNT      // dexopt parameters.
-                                     + 1;                      // null termination.
-    const char* argv[kOutArguments];
-    if (static_cast<size_t>(argc) !=  kInArguments - 1 /* null termination */) {
-        LOG(ERROR) << "Unexpected argument size "
-                   << argc
-                   << " vs "
-                   << (kInArguments - 1);
-        for (size_t i = 0; i < static_cast<size_t>(argc); ++i) {
-            if (arg[i] == nullptr) {
-                LOG(ERROR) << "(null)";
-            } else {
-                LOG(ERROR) << "\"" << arg[i] << "\"";
-            }
-        }
-        exit(206);
-    }
+    // Incoming:  cmd + status-fd + target-slot + cmd... + null      | Incoming | = argc + 1
+    // Outgoing:  cmd             + target-slot + cmd... + null      | Outgoing | = argc
+    const char** argv = new const char*[argc];
+
     argv[0] = "/system/bin/otapreopt";
 
     // The first parameter is the status file descriptor, skip.
-
-    for (size_t i = 1; i <= kOutArguments - 2 /* cmd + null */; ++i) {
-        argv[i] = arg[i + 1];
+    for (size_t i = 2; i <= static_cast<size_t>(argc); ++i) {
+        argv[i - 1] = arg[i];
     }
-    argv[kOutArguments - 1] = nullptr;
 
-    execv(argv[0], (char * const *)argv);
+    execv(argv[0], static_cast<char * const *>(const_cast<char**>(argv)));
     PLOG(ERROR) << "execv(OTAPREOPT) failed.";
     exit(99);
 }
diff --git a/include/gui/IGraphicBufferProducer.h b/include/gui/IGraphicBufferProducer.h
index 5810335..9250806 100644
--- a/include/gui/IGraphicBufferProducer.h
+++ b/include/gui/IGraphicBufferProducer.h
@@ -487,6 +487,7 @@
     // is considered a no-op.
     //
     // Return of a value other than NO_ERROR means an error has occurred:
+    // * NO_INIT - the producer is not connected
     // * BAD_VALUE - one of the following has occurred:
     //             * the api specified does not match the one that was connected
     //             * api was out of range (see above).
diff --git a/include/ui/Gralloc1.h b/include/ui/Gralloc1.h
deleted file mode 100644
index 90713b3..0000000
--- a/include/ui/Gralloc1.h
+++ /dev/null
@@ -1,295 +0,0 @@
-/*
- * Copyright 2016 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_UI_GRALLOC1_H
-#define ANDROID_UI_GRALLOC1_H
-
-#define GRALLOC1_LOG_TAG "Gralloc1"
-
-#include <functional>
-#include <memory>
-#include <unordered_set>
-
-#include <log/log.h>
-
-#include <ui/Fence.h>
-
-#include <hardware/gralloc1.h>
-
-
-namespace std {
-    template <>
-    struct hash<gralloc1_capability_t> {
-        size_t operator()(gralloc1_capability_t capability) const {
-            return std::hash<int32_t>()(static_cast<int32_t>(capability));
-        }
-    };
-}
-
-namespace android {
-class GraphicBuffer;
-class Fence;
-class GraphicBuffer;
-class Gralloc1On0Adapter;
-} // namespace android
-
-
-// This is not an "official" capability (i.e., it is not found in gralloc1.h),
-// but we will use it to detect that we are running through the adapter, which
-// is capable of collaborating with GraphicBuffer such that queries on a
-// buffer_handle_t succeed
-static const auto GRALLOC1_CAPABILITY_ON_ADAPTER =
-        static_cast<gralloc1_capability_t>(GRALLOC1_LAST_CAPABILITY + 1);
-
-static const auto GRALLOC1_FUNCTION_RETAIN_GRAPHIC_BUFFER =
-        static_cast<gralloc1_function_descriptor_t>(GRALLOC1_LAST_FUNCTION + 1);
-static const auto GRALLOC1_FUNCTION_ALLOCATE_WITH_ID =
-        static_cast<gralloc1_function_descriptor_t>(GRALLOC1_LAST_FUNCTION + 2);
-static const auto GRALLOC1_FUNCTION_LOCK_YCBCR =
-        static_cast<gralloc1_function_descriptor_t>(GRALLOC1_LAST_FUNCTION + 3);
-static const auto GRALLOC1_LAST_ADAPTER_FUNCTION = GRALLOC1_FUNCTION_LOCK_YCBCR;
-
-typedef gralloc1_error_t (*GRALLOC1_PFN_RETAIN_GRAPHIC_BUFFER)(
-        gralloc1_device_t* device, const android::GraphicBuffer* buffer);
-typedef gralloc1_error_t (*GRALLOC1_PFN_ALLOCATE_WITH_ID)(
-        gralloc1_device_t* device, gralloc1_buffer_descriptor_t descriptor,
-        gralloc1_backing_store_t id, buffer_handle_t* outBuffer);
-typedef int32_t /*gralloc1_error_t*/ (*GRALLOC1_PFN_LOCK_YCBCR)(
-        gralloc1_device_t* device, buffer_handle_t buffer,
-        uint64_t /*gralloc1_producer_usage_t*/ producerUsage,
-        uint64_t /*gralloc1_consumer_usage_t*/ consumerUsage,
-        const gralloc1_rect_t* accessRegion, struct android_ycbcr* outYCbCr,
-        int32_t acquireFence);
-
-
-namespace android {
-namespace Gralloc1 {
-
-class Device;
-
-class Descriptor {
-public:
-    Descriptor(Device& device, gralloc1_buffer_descriptor_t deviceId)
-      : mShimDevice(device),
-        mDeviceId(deviceId),
-        mWidth(0),
-        mHeight(0),
-        mFormat(static_cast<android_pixel_format_t>(0)),
-        mLayerCount(0),
-        mProducerUsage(GRALLOC1_PRODUCER_USAGE_NONE),
-        mConsumerUsage(GRALLOC1_CONSUMER_USAGE_NONE) {}
-
-    ~Descriptor();
-
-    gralloc1_buffer_descriptor_t getDeviceId() const { return mDeviceId; }
-
-    gralloc1_error_t setDimensions(uint32_t width, uint32_t height);
-    gralloc1_error_t setFormat(android_pixel_format_t format);
-    gralloc1_error_t setLayerCount(uint32_t layerCount);
-    gralloc1_error_t setProducerUsage(gralloc1_producer_usage_t usage);
-    gralloc1_error_t setConsumerUsage(gralloc1_consumer_usage_t usage);
-
-private:
-    Device& mShimDevice;
-    const gralloc1_buffer_descriptor_t mDeviceId;
-
-    uint32_t mWidth;
-    uint32_t mHeight;
-    android_pixel_format_t mFormat;
-    uint32_t mLayerCount;
-    gralloc1_producer_usage_t mProducerUsage;
-    gralloc1_consumer_usage_t mConsumerUsage;
-
-}; // Descriptor
-
-class Device {
-    friend class Gralloc1::Descriptor;
-
-public:
-    Device(gralloc1_device_t* device);
-
-    bool hasCapability(gralloc1_capability_t capability) const;
-
-    std::string dump();
-
-    std::shared_ptr<Descriptor> createDescriptor();
-
-    gralloc1_error_t allocate(
-            const std::vector<std::shared_ptr<const Descriptor>>& descriptors,
-            std::vector<buffer_handle_t>* outBuffers);
-    gralloc1_error_t allocate(
-            const std::shared_ptr<const Descriptor>& descriptor,
-            gralloc1_backing_store_t id, buffer_handle_t* outBuffer);
-
-    gralloc1_error_t retain(buffer_handle_t buffer);
-    gralloc1_error_t retain(const GraphicBuffer* buffer);
-
-    gralloc1_error_t release(buffer_handle_t buffer);
-
-    gralloc1_error_t getDimensions(buffer_handle_t buffer,
-            uint32_t* outWidth, uint32_t* outHeight);
-    gralloc1_error_t getFormat(buffer_handle_t buffer,
-            int32_t* outFormat);
-    gralloc1_error_t getLayerCount(buffer_handle_t buffer,
-            uint32_t* outLayerCount);
-    gralloc1_error_t getProducerUsage(buffer_handle_t buffer,
-            uint64_t* outProducerUsage);
-    gralloc1_error_t getConsumerUsage(buffer_handle_t buffer,
-            uint64_t* outConsumerUsage);
-    gralloc1_error_t getBackingStore(buffer_handle_t buffer,
-            uint64_t* outBackingStore);
-    gralloc1_error_t getStride(buffer_handle_t buffer, uint32_t* outStride);
-    gralloc1_error_t getNumFlexPlanes(buffer_handle_t buffer,
-            uint32_t* outNumPlanes);
-
-    gralloc1_error_t lock(buffer_handle_t buffer,
-            gralloc1_producer_usage_t producerUsage,
-            gralloc1_consumer_usage_t consumerUsage,
-            const gralloc1_rect_t* accessRegion, void** outData,
-            const sp<Fence>& acquireFence);
-    gralloc1_error_t lockFlex(buffer_handle_t buffer,
-            gralloc1_producer_usage_t producerUsage,
-            gralloc1_consumer_usage_t consumerUsage,
-            const gralloc1_rect_t* accessRegion,
-            struct android_flex_layout* outData, const sp<Fence>& acquireFence);
-    gralloc1_error_t lockYCbCr(buffer_handle_t buffer,
-            gralloc1_producer_usage_t producerUsage,
-            gralloc1_consumer_usage_t consumerUsage,
-            const gralloc1_rect_t* accessRegion, struct android_ycbcr* outData,
-            const sp<Fence>& acquireFence);
-
-    gralloc1_error_t unlock(buffer_handle_t buffer, sp<Fence>* outFence);
-
-private:
-    std::unordered_set<gralloc1_capability_t> loadCapabilities();
-
-    bool loadFunctions();
-
-    template <typename LockType, typename OutType>
-    gralloc1_error_t lockHelper(LockType pfn, buffer_handle_t buffer,
-            gralloc1_producer_usage_t producerUsage,
-            gralloc1_consumer_usage_t consumerUsage,
-            const gralloc1_rect_t* accessRegion, OutType* outData,
-            const sp<Fence>& acquireFence) {
-        int32_t intError = pfn(mDevice, buffer,
-                static_cast<uint64_t>(producerUsage),
-                static_cast<uint64_t>(consumerUsage), accessRegion, outData,
-                acquireFence->dup());
-        return static_cast<gralloc1_error_t>(intError);
-    }
-
-    gralloc1_device_t* const mDevice;
-
-    const std::unordered_set<gralloc1_capability_t> mCapabilities;
-
-    template <typename PFN, gralloc1_function_descriptor_t descriptor>
-    struct FunctionLoader {
-        FunctionLoader() : pfn(nullptr) {}
-
-        bool load(gralloc1_device_t* device, bool errorIfNull) {
-            gralloc1_function_pointer_t rawPointer =
-                    device->getFunction(device, descriptor);
-            pfn = reinterpret_cast<PFN>(rawPointer);
-            if (errorIfNull && !rawPointer) {
-                ALOG(LOG_ERROR, GRALLOC1_LOG_TAG,
-                        "Failed to load function pointer %d", descriptor);
-            }
-            return rawPointer != nullptr;
-        }
-
-        template <typename ...Args>
-        typename std::result_of<PFN(Args...)>::type operator()(Args... args) {
-            return pfn(args...);
-        }
-
-        PFN pfn;
-    };
-
-    // Function pointers
-    struct Functions {
-        FunctionLoader<GRALLOC1_PFN_DUMP, GRALLOC1_FUNCTION_DUMP> dump;
-        FunctionLoader<GRALLOC1_PFN_CREATE_DESCRIPTOR,
-                GRALLOC1_FUNCTION_CREATE_DESCRIPTOR> createDescriptor;
-        FunctionLoader<GRALLOC1_PFN_DESTROY_DESCRIPTOR,
-                GRALLOC1_FUNCTION_DESTROY_DESCRIPTOR> destroyDescriptor;
-        FunctionLoader<GRALLOC1_PFN_SET_CONSUMER_USAGE,
-                GRALLOC1_FUNCTION_SET_CONSUMER_USAGE> setConsumerUsage;
-        FunctionLoader<GRALLOC1_PFN_SET_DIMENSIONS,
-                GRALLOC1_FUNCTION_SET_DIMENSIONS> setDimensions;
-        FunctionLoader<GRALLOC1_PFN_SET_FORMAT,
-                GRALLOC1_FUNCTION_SET_FORMAT> setFormat;
-        FunctionLoader<GRALLOC1_PFN_SET_LAYER_COUNT,
-                GRALLOC1_FUNCTION_SET_LAYER_COUNT> setLayerCount;
-        FunctionLoader<GRALLOC1_PFN_SET_PRODUCER_USAGE,
-                GRALLOC1_FUNCTION_SET_PRODUCER_USAGE> setProducerUsage;
-        FunctionLoader<GRALLOC1_PFN_GET_BACKING_STORE,
-                GRALLOC1_FUNCTION_GET_BACKING_STORE> getBackingStore;
-        FunctionLoader<GRALLOC1_PFN_GET_CONSUMER_USAGE,
-                GRALLOC1_FUNCTION_GET_CONSUMER_USAGE> getConsumerUsage;
-        FunctionLoader<GRALLOC1_PFN_GET_DIMENSIONS,
-                GRALLOC1_FUNCTION_GET_DIMENSIONS> getDimensions;
-        FunctionLoader<GRALLOC1_PFN_GET_FORMAT,
-                GRALLOC1_FUNCTION_GET_FORMAT> getFormat;
-        FunctionLoader<GRALLOC1_PFN_GET_LAYER_COUNT,
-                GRALLOC1_FUNCTION_GET_LAYER_COUNT> getLayerCount;
-        FunctionLoader<GRALLOC1_PFN_GET_PRODUCER_USAGE,
-                GRALLOC1_FUNCTION_GET_PRODUCER_USAGE> getProducerUsage;
-        FunctionLoader<GRALLOC1_PFN_GET_STRIDE,
-                GRALLOC1_FUNCTION_GET_STRIDE> getStride;
-        FunctionLoader<GRALLOC1_PFN_ALLOCATE,
-                GRALLOC1_FUNCTION_ALLOCATE> allocate;
-        FunctionLoader<GRALLOC1_PFN_RETAIN,
-                GRALLOC1_FUNCTION_RETAIN> retain;
-        FunctionLoader<GRALLOC1_PFN_RELEASE,
-                GRALLOC1_FUNCTION_RELEASE> release;
-        FunctionLoader<GRALLOC1_PFN_GET_NUM_FLEX_PLANES,
-                GRALLOC1_FUNCTION_GET_NUM_FLEX_PLANES> getNumFlexPlanes;
-        FunctionLoader<GRALLOC1_PFN_LOCK,
-                GRALLOC1_FUNCTION_LOCK> lock;
-        FunctionLoader<GRALLOC1_PFN_LOCK_FLEX,
-                GRALLOC1_FUNCTION_LOCK_FLEX> lockFlex;
-        FunctionLoader<GRALLOC1_PFN_LOCK_YCBCR,
-                GRALLOC1_FUNCTION_LOCK_YCBCR> lockYCbCr;
-        FunctionLoader<GRALLOC1_PFN_UNLOCK,
-                GRALLOC1_FUNCTION_UNLOCK> unlock;
-
-        // Adapter-only functions
-        FunctionLoader<GRALLOC1_PFN_RETAIN_GRAPHIC_BUFFER,
-                GRALLOC1_FUNCTION_RETAIN_GRAPHIC_BUFFER> retainGraphicBuffer;
-        FunctionLoader<GRALLOC1_PFN_ALLOCATE_WITH_ID,
-                GRALLOC1_FUNCTION_ALLOCATE_WITH_ID> allocateWithId;
-    } mFunctions;
-
-}; // class android::Gralloc1::Device
-
-class Loader
-{
-public:
-    Loader();
-    ~Loader();
-
-    std::unique_ptr<Device> getDevice();
-
-private:
-    static std::unique_ptr<Gralloc1On0Adapter> mAdapter;
-    std::unique_ptr<Device> mDevice;
-};
-
-} // namespace android::Gralloc1
-
-} // namespace android
-
-#endif
diff --git a/include/ui/Gralloc1On0Adapter.h b/include/ui/Gralloc1On0Adapter.h
deleted file mode 100644
index 6379a08..0000000
--- a/include/ui/Gralloc1On0Adapter.h
+++ /dev/null
@@ -1,478 +0,0 @@
-/*
- * Copyright 2016 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_UI_GRALLOC_1_ON_0_ADAPTER_H
-#define ANDROID_UI_GRALLOC_1_ON_0_ADAPTER_H
-
-#include <log/log.h>
-
-#include <ui/Fence.h>
-
-#include <hardware/gralloc.h>
-#include <hardware/gralloc1.h>
-
-#include <mutex>
-#include <string>
-#include <unordered_map>
-#include <vector>
-
-namespace android {
-class GraphicBuffer;
-} // namespace android
-
-struct gralloc_module_t;
-
-namespace android {
-
-class Gralloc1On0Adapter : public gralloc1_device_t
-{
-public:
-    Gralloc1On0Adapter(const hw_module_t* module);
-    ~Gralloc1On0Adapter();
-
-    gralloc1_device_t* getDevice() {
-        return static_cast<gralloc1_device_t*>(this);
-    }
-
-private:
-    static inline Gralloc1On0Adapter* getAdapter(gralloc1_device_t* device) {
-        return static_cast<Gralloc1On0Adapter*>(device);
-    }
-
-    // getCapabilities
-
-    void doGetCapabilities(uint32_t* outCount,
-            int32_t* /*gralloc1_capability_t*/ outCapabilities);
-    static void getCapabilitiesHook(gralloc1_device_t* device,
-            uint32_t* outCount,
-            int32_t* /*gralloc1_capability_t*/ outCapabilities) {
-        getAdapter(device)->doGetCapabilities(outCount, outCapabilities);
-    }
-
-    // getFunction
-
-    gralloc1_function_pointer_t doGetFunction(
-            int32_t /*gralloc1_function_descriptor_t*/ descriptor);
-    static gralloc1_function_pointer_t getFunctionHook(
-            gralloc1_device_t* device,
-            int32_t /*gralloc1_function_descriptor_t*/ descriptor) {
-        return getAdapter(device)->doGetFunction(descriptor);
-    }
-
-    // dump
-
-    void dump(uint32_t* outSize, char* outBuffer);
-    static void dumpHook(gralloc1_device_t* device, uint32_t* outSize,
-            char* outBuffer) {
-        return getAdapter(device)->dump(outSize, outBuffer);
-    }
-    std::string mCachedDump;
-
-    // Buffer descriptor lifecycle functions
-
-    struct Descriptor;
-
-    gralloc1_error_t createDescriptor(
-            gralloc1_buffer_descriptor_t* outDescriptor);
-    static int32_t createDescriptorHook(gralloc1_device_t* device,
-            gralloc1_buffer_descriptor_t* outDescriptor) {
-        auto error = getAdapter(device)->createDescriptor(outDescriptor);
-        return static_cast<int32_t>(error);
-    }
-
-    gralloc1_error_t destroyDescriptor(gralloc1_buffer_descriptor_t descriptor);
-    static int32_t destroyDescriptorHook(gralloc1_device_t* device,
-            gralloc1_buffer_descriptor_t descriptor) {
-        auto error = getAdapter(device)->destroyDescriptor(descriptor);
-        return static_cast<int32_t>(error);
-    }
-
-    // Buffer descriptor modification functions
-
-    struct Descriptor : public std::enable_shared_from_this<Descriptor> {
-        Descriptor(Gralloc1On0Adapter* _adapter,
-                gralloc1_buffer_descriptor_t _id)
-          : adapter(_adapter),
-            id(_id),
-            width(0),
-            height(0),
-            format(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED),
-            layerCount(1),
-            producerUsage(GRALLOC1_PRODUCER_USAGE_NONE),
-            consumerUsage(GRALLOC1_CONSUMER_USAGE_NONE) {}
-
-        gralloc1_error_t setDimensions(uint32_t w, uint32_t h) {
-            width = w;
-            height = h;
-            return GRALLOC1_ERROR_NONE;
-        }
-
-        gralloc1_error_t setFormat(int32_t f) {
-            format = f;
-            return GRALLOC1_ERROR_NONE;
-        }
-
-        gralloc1_error_t setLayerCount(uint32_t lc) {
-            layerCount = lc;
-            return GRALLOC1_ERROR_NONE;
-        }
-
-        gralloc1_error_t setProducerUsage(gralloc1_producer_usage_t usage) {
-            producerUsage = usage;
-            return GRALLOC1_ERROR_NONE;
-        }
-
-        gralloc1_error_t setConsumerUsage(gralloc1_consumer_usage_t usage) {
-            consumerUsage = usage;
-            return GRALLOC1_ERROR_NONE;
-        }
-
-        Gralloc1On0Adapter* const adapter;
-        const gralloc1_buffer_descriptor_t id;
-
-        uint32_t width;
-        uint32_t height;
-        int32_t format;
-        uint32_t layerCount;
-        gralloc1_producer_usage_t producerUsage;
-        gralloc1_consumer_usage_t consumerUsage;
-    };
-
-    template <typename ...Args>
-    static int32_t callDescriptorFunction(gralloc1_device_t* device,
-            gralloc1_buffer_descriptor_t descriptorId,
-            gralloc1_error_t (Descriptor::*member)(Args...), Args... args) {
-        auto descriptor = getAdapter(device)->getDescriptor(descriptorId);
-        if (!descriptor) {
-            return static_cast<int32_t>(GRALLOC1_ERROR_BAD_DESCRIPTOR);
-        }
-        auto error = ((*descriptor).*member)(std::forward<Args>(args)...);
-        return static_cast<int32_t>(error);
-    }
-
-    static int32_t setConsumerUsageHook(gralloc1_device_t* device,
-            gralloc1_buffer_descriptor_t descriptorId, uint64_t intUsage) {
-        auto usage = static_cast<gralloc1_consumer_usage_t>(intUsage);
-        return callDescriptorFunction(device, descriptorId,
-                &Descriptor::setConsumerUsage, usage);
-    }
-
-    static int32_t setDimensionsHook(gralloc1_device_t* device,
-            gralloc1_buffer_descriptor_t descriptorId, uint32_t width,
-            uint32_t height) {
-        return callDescriptorFunction(device, descriptorId,
-                &Descriptor::setDimensions, width, height);
-    }
-
-    static int32_t setFormatHook(gralloc1_device_t* device,
-            gralloc1_buffer_descriptor_t descriptorId, int32_t format) {
-        return callDescriptorFunction(device, descriptorId,
-                &Descriptor::setFormat, format);
-    }
-
-    static int32_t setLayerCountHook(gralloc1_device_t* device,
-            gralloc1_buffer_descriptor_t descriptorId, uint32_t layerCount) {
-        return callDescriptorFunction(device, descriptorId,
-                &Descriptor::setLayerCount, layerCount);
-    }
-
-    static int32_t setProducerUsageHook(gralloc1_device_t* device,
-            gralloc1_buffer_descriptor_t descriptorId, uint64_t intUsage) {
-        auto usage = static_cast<gralloc1_producer_usage_t>(intUsage);
-        return callDescriptorFunction(device, descriptorId,
-                &Descriptor::setProducerUsage, usage);
-    }
-
-    // Buffer handle query functions
-
-    class Buffer {
-    public:
-        Buffer(buffer_handle_t handle, gralloc1_backing_store_t store,
-                const Descriptor& descriptor, uint32_t stride,
-                bool wasAllocated);
-
-        buffer_handle_t getHandle() const { return mHandle; }
-
-        void retain() { ++mReferenceCount; }
-
-        // Returns true if the reference count has dropped to 0, indicating that
-        // the buffer needs to be released
-        bool release() { return --mReferenceCount == 0; }
-
-        bool wasAllocated() const { return mWasAllocated; }
-
-        gralloc1_error_t getBackingStore(
-                gralloc1_backing_store_t* outStore) const {
-            *outStore = mStore;
-            return GRALLOC1_ERROR_NONE;
-        }
-
-        gralloc1_error_t getConsumerUsage(
-                gralloc1_consumer_usage_t* outUsage) const {
-            *outUsage = mDescriptor.consumerUsage;
-            return GRALLOC1_ERROR_NONE;
-        }
-
-        gralloc1_error_t getDimensions(uint32_t* outWidth,
-                uint32_t* outHeight) const {
-            *outWidth = mDescriptor.width;
-            *outHeight = mDescriptor.height;
-            return GRALLOC1_ERROR_NONE;
-        }
-
-        gralloc1_error_t getFormat(int32_t* outFormat) const {
-            *outFormat = mDescriptor.format;
-            return GRALLOC1_ERROR_NONE;
-        }
-
-        gralloc1_error_t getLayerCount(uint32_t* outLayerCount) const {
-            *outLayerCount = mDescriptor.layerCount;
-            return GRALLOC1_ERROR_NONE;
-        }
-
-        gralloc1_error_t getNumFlexPlanes(uint32_t* outNumPlanes) const {
-            // TODO: This is conservative, and we could do better by examining
-            // the format, but it won't hurt anything for now
-            *outNumPlanes = 4;
-            return GRALLOC1_ERROR_NONE;
-        }
-
-        gralloc1_error_t getProducerUsage(
-                gralloc1_producer_usage_t* outUsage) const {
-            *outUsage = mDescriptor.producerUsage;
-            return GRALLOC1_ERROR_NONE;
-        }
-
-        gralloc1_error_t getStride(uint32_t* outStride) const {
-            *outStride = mStride;
-            return GRALLOC1_ERROR_NONE;
-        }
-
-    private:
-
-        const buffer_handle_t mHandle;
-        size_t mReferenceCount;
-
-        // Since we're adapting to gralloc0, there will always be a 1:1
-        // correspondence between buffer handles and backing stores, and the
-        // backing store ID will be the same as the GraphicBuffer unique ID
-        const gralloc1_backing_store_t mStore;
-
-        const Descriptor mDescriptor;
-        const uint32_t mStride;
-
-        // Whether this buffer allocated in this process (as opposed to just
-        // being retained here), which determines whether to free or unregister
-        // the buffer when this Buffer is released
-        const bool mWasAllocated;
-    };
-
-    template <typename ...Args>
-    static int32_t callBufferFunction(gralloc1_device_t* device,
-            buffer_handle_t bufferHandle,
-            gralloc1_error_t (Buffer::*member)(Args...) const, Args... args) {
-        auto buffer = getAdapter(device)->getBuffer(bufferHandle);
-        if (!buffer) {
-            return static_cast<int32_t>(GRALLOC1_ERROR_BAD_HANDLE);
-        }
-        auto error = ((*buffer).*member)(std::forward<Args>(args)...);
-        return static_cast<int32_t>(error);
-    }
-
-    template <typename MF, MF memFunc, typename ...Args>
-    static int32_t bufferHook(gralloc1_device_t* device,
-            buffer_handle_t bufferHandle, Args... args) {
-        return Gralloc1On0Adapter::callBufferFunction(device, bufferHandle,
-                memFunc, std::forward<Args>(args)...);
-    }
-
-    static int32_t getConsumerUsageHook(gralloc1_device_t* device,
-            buffer_handle_t bufferHandle, uint64_t* outUsage) {
-        auto usage = GRALLOC1_CONSUMER_USAGE_NONE;
-        auto error = callBufferFunction(device, bufferHandle,
-                &Buffer::getConsumerUsage, &usage);
-        if (error == GRALLOC1_ERROR_NONE) {
-            *outUsage = static_cast<uint64_t>(usage);
-        }
-        return error;
-    }
-
-    static int32_t getProducerUsageHook(gralloc1_device_t* device,
-            buffer_handle_t bufferHandle, uint64_t* outUsage) {
-        auto usage = GRALLOC1_PRODUCER_USAGE_NONE;
-        auto error = callBufferFunction(device, bufferHandle,
-                &Buffer::getProducerUsage, &usage);
-        if (error == GRALLOC1_ERROR_NONE) {
-            *outUsage = static_cast<uint64_t>(usage);
-        }
-        return error;
-    }
-
-    // Buffer management functions
-
-    // We don't provide GRALLOC1_FUNCTION_ALLOCATE, since this should always be
-    // called through GRALLOC1_FUNCTION_ALLOCATE_WITH_ID
-    gralloc1_error_t allocate(
-            const std::shared_ptr<Descriptor>& descriptor,
-            gralloc1_backing_store_t id,
-            buffer_handle_t* outBufferHandle);
-    static gralloc1_error_t allocateWithIdHook(gralloc1_device_t* device,
-            gralloc1_buffer_descriptor_t descriptors,
-            gralloc1_backing_store_t id, buffer_handle_t* outBuffer);
-
-    gralloc1_error_t retain(const std::shared_ptr<Buffer>& buffer);
-    gralloc1_error_t release(const std::shared_ptr<Buffer>& buffer);
-
-    // Member function pointer 'member' will either be retain or release
-    template <gralloc1_error_t (Gralloc1On0Adapter::*member)(
-            const std::shared_ptr<Buffer>& buffer)>
-    static int32_t managementHook(gralloc1_device_t* device,
-            buffer_handle_t bufferHandle) {
-        auto adapter = getAdapter(device);
-
-        auto buffer = adapter->getBuffer(bufferHandle);
-        if (!buffer) {
-            return static_cast<int32_t>(GRALLOC1_ERROR_BAD_HANDLE);
-        }
-
-        auto error = ((*adapter).*member)(buffer);
-        return static_cast<int32_t>(error);
-    }
-
-    gralloc1_error_t retain(const GraphicBuffer* buffer);
-    static gralloc1_error_t retainGraphicBufferHook(gralloc1_device_t* device,
-            const GraphicBuffer* buffer) {
-        auto adapter = getAdapter(device);
-        return adapter->retain(buffer);
-    }
-
-    // Buffer access functions
-
-    gralloc1_error_t lock(const std::shared_ptr<Buffer>& buffer,
-            gralloc1_producer_usage_t producerUsage,
-            gralloc1_consumer_usage_t consumerUsage,
-            const gralloc1_rect_t& accessRegion, void** outData,
-            const sp<Fence>& acquireFence);
-    gralloc1_error_t lockFlex(const std::shared_ptr<Buffer>& buffer,
-            gralloc1_producer_usage_t producerUsage,
-            gralloc1_consumer_usage_t consumerUsage,
-            const gralloc1_rect_t& accessRegion,
-            struct android_flex_layout* outFlex,
-            const sp<Fence>& acquireFence);
-    gralloc1_error_t lockYCbCr(const std::shared_ptr<Buffer>& buffer,
-            gralloc1_producer_usage_t producerUsage,
-            gralloc1_consumer_usage_t consumerUsage,
-            const gralloc1_rect_t& accessRegion,
-            struct android_ycbcr* outFlex,
-            const sp<Fence>& acquireFence);
-
-    template <typename OUT, gralloc1_error_t (Gralloc1On0Adapter::*member)(
-            const std::shared_ptr<Buffer>&, gralloc1_producer_usage_t,
-            gralloc1_consumer_usage_t, const gralloc1_rect_t&, OUT*,
-            const sp<Fence>&)>
-    static int32_t lockHook(gralloc1_device_t* device,
-            buffer_handle_t bufferHandle,
-            uint64_t /*gralloc1_producer_usage_t*/ uintProducerUsage,
-            uint64_t /*gralloc1_consumer_usage_t*/ uintConsumerUsage,
-            const gralloc1_rect_t* accessRegion, OUT* outData,
-            int32_t acquireFenceFd) {
-        auto adapter = getAdapter(device);
-
-        // Exactly one of producer and consumer usage must be *_USAGE_NONE,
-        // but we can't check this until the upper levels of the framework
-        // correctly distinguish between producer and consumer usage
-        /*
-        bool hasProducerUsage =
-                uintProducerUsage != GRALLOC1_PRODUCER_USAGE_NONE;
-        bool hasConsumerUsage =
-                uintConsumerUsage != GRALLOC1_CONSUMER_USAGE_NONE;
-        if (hasProducerUsage && hasConsumerUsage ||
-                !hasProducerUsage && !hasConsumerUsage) {
-            return static_cast<int32_t>(GRALLOC1_ERROR_BAD_VALUE);
-        }
-        */
-
-        auto producerUsage =
-                static_cast<gralloc1_producer_usage_t>(uintProducerUsage);
-        auto consumerUsage =
-                static_cast<gralloc1_consumer_usage_t>(uintConsumerUsage);
-
-        if (!outData) {
-            const auto producerCpuUsage = GRALLOC1_PRODUCER_USAGE_CPU_READ |
-                    GRALLOC1_PRODUCER_USAGE_CPU_WRITE;
-            if ((producerUsage & producerCpuUsage) != 0) {
-                return static_cast<int32_t>(GRALLOC1_ERROR_BAD_VALUE);
-            }
-            if ((consumerUsage & GRALLOC1_CONSUMER_USAGE_CPU_READ) != 0) {
-                return static_cast<int32_t>(GRALLOC1_ERROR_BAD_VALUE);
-            }
-        }
-
-        auto buffer = adapter->getBuffer(bufferHandle);
-        if (!buffer) {
-            return static_cast<int32_t>(GRALLOC1_ERROR_BAD_HANDLE);
-        }
-
-        if (!accessRegion) {
-            ALOGE("accessRegion is null");
-            return static_cast<int32_t>(GRALLOC1_ERROR_BAD_VALUE);
-        }
-
-        sp<Fence> acquireFence{new Fence(acquireFenceFd)};
-        auto error = ((*adapter).*member)(buffer, producerUsage, consumerUsage,
-                *accessRegion, outData, acquireFence);
-        return static_cast<int32_t>(error);
-    }
-
-    gralloc1_error_t unlock(const std::shared_ptr<Buffer>& buffer,
-            sp<Fence>* outReleaseFence);
-    static int32_t unlockHook(gralloc1_device_t* device,
-            buffer_handle_t bufferHandle, int32_t* outReleaseFenceFd) {
-        auto adapter = getAdapter(device);
-
-        auto buffer = adapter->getBuffer(bufferHandle);
-        if (!buffer) {
-            return static_cast<int32_t>(GRALLOC1_ERROR_BAD_HANDLE);
-        }
-
-        sp<Fence> releaseFence = Fence::NO_FENCE;
-        auto error = adapter->unlock(buffer, &releaseFence);
-        if (error == GRALLOC1_ERROR_NONE) {
-            *outReleaseFenceFd = releaseFence->dup();
-        }
-        return static_cast<int32_t>(error);
-    }
-
-    // Adapter internals
-    const gralloc_module_t* mModule;
-    uint8_t mMinorVersion;
-    alloc_device_t* mDevice;
-
-    std::shared_ptr<Descriptor> getDescriptor(
-            gralloc1_buffer_descriptor_t descriptorId);
-    std::shared_ptr<Buffer> getBuffer(buffer_handle_t bufferHandle);
-
-    static std::atomic<gralloc1_buffer_descriptor_t> sNextBufferDescriptorId;
-    std::mutex mDescriptorMutex;
-    std::unordered_map<gralloc1_buffer_descriptor_t,
-            std::shared_ptr<Descriptor>> mDescriptors;
-    std::mutex mBufferMutex;
-    std::unordered_map<buffer_handle_t, std::shared_ptr<Buffer>> mBuffers;
-};
-
-} // namespace android
-
-#endif
diff --git a/include/ui/Gralloc2.h b/include/ui/Gralloc2.h
index c59d327..f826b92 100644
--- a/include/ui/Gralloc2.h
+++ b/include/ui/Gralloc2.h
@@ -41,9 +41,6 @@
 public:
     Mapper();
 
-    // this will be removed and Mapper will be always valid
-    bool valid() const { return (mMapper != nullptr); }
-
     Error createDescriptor(
             const IMapper::BufferDescriptorInfo& descriptorInfo,
             BufferDescriptor* outDescriptor) const;
@@ -84,9 +81,6 @@
     // time.
     Allocator(const Mapper& mapper);
 
-    // this will be removed and Allocator will be always valid
-    bool valid() const { return (mAllocator != nullptr); }
-
     std::string dumpDebugInfo() const;
 
     /*
diff --git a/include/ui/GraphicBufferAllocator.h b/include/ui/GraphicBufferAllocator.h
index 95eb8fd..c4cbfc4 100644
--- a/include/ui/GraphicBufferAllocator.h
+++ b/include/ui/GraphicBufferAllocator.h
@@ -25,14 +25,15 @@
 
 #include <cutils/native_handle.h>
 
+#include <system/window.h>
+
+#include <ui/PixelFormat.h>
+
 #include <utils/Errors.h>
 #include <utils/KeyedVector.h>
 #include <utils/Mutex.h>
 #include <utils/Singleton.h>
 
-#include <ui/Gralloc1.h>
-#include <ui/PixelFormat.h>
-
 namespace android {
 
 namespace Gralloc2 {
@@ -45,25 +46,6 @@
 class GraphicBufferAllocator : public Singleton<GraphicBufferAllocator>
 {
 public:
-    enum {
-        USAGE_SW_READ_NEVER     = GRALLOC1_CONSUMER_USAGE_CPU_READ_NEVER,
-        USAGE_SW_READ_RARELY    = GRALLOC1_CONSUMER_USAGE_CPU_READ,
-        USAGE_SW_READ_OFTEN     = GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN,
-        USAGE_SW_READ_MASK      = GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN,
-
-        USAGE_SW_WRITE_NEVER    = GRALLOC1_PRODUCER_USAGE_CPU_WRITE_NEVER,
-        USAGE_SW_WRITE_RARELY   = GRALLOC1_PRODUCER_USAGE_CPU_WRITE,
-        USAGE_SW_WRITE_OFTEN    = GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN,
-        USAGE_SW_WRITE_MASK     = GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN,
-
-        USAGE_SOFTWARE_MASK     = USAGE_SW_READ_MASK|USAGE_SW_WRITE_MASK,
-
-        USAGE_HW_TEXTURE        = GRALLOC1_CONSUMER_USAGE_GPU_TEXTURE,
-        USAGE_HW_RENDER         = GRALLOC1_PRODUCER_USAGE_GPU_RENDER_TARGET,
-        USAGE_HW_2D             = 0x00000400, // Deprecated
-        USAGE_HW_MASK           = 0x00071F00, // Deprecated
-    };
-
     static inline GraphicBufferAllocator& get() { return getInstance(); }
 
     status_t allocate(uint32_t w, uint32_t h, PixelFormat format,
@@ -98,9 +80,6 @@
 
     GraphicBufferMapper& mMapper;
     const std::unique_ptr<const Gralloc2::Allocator> mAllocator;
-
-    std::unique_ptr<Gralloc1::Loader> mLoader;
-    std::unique_ptr<Gralloc1::Device> mDevice;
 };
 
 // ---------------------------------------------------------------------------
diff --git a/include/ui/GraphicBufferMapper.h b/include/ui/GraphicBufferMapper.h
index d69f8fc..e0702e9 100644
--- a/include/ui/GraphicBufferMapper.h
+++ b/include/ui/GraphicBufferMapper.h
@@ -22,8 +22,6 @@
 
 #include <memory>
 
-#include <ui/Gralloc1.h>
-
 #include <utils/Singleton.h>
 
 
@@ -52,9 +50,6 @@
     status_t importBuffer(buffer_handle_t rawHandle,
             buffer_handle_t* outHandle);
 
-    // This is temporary and will be removed soon
-    status_t importBuffer(const GraphicBuffer* buffer);
-
     status_t freeBuffer(buffer_handle_t handle);
 
     status_t lock(buffer_handle_t handle,
@@ -89,9 +84,6 @@
     GraphicBufferMapper();
 
     const std::unique_ptr<const Gralloc2::Mapper> mMapper;
-
-    std::unique_ptr<Gralloc1::Loader> mLoader;
-    std::unique_ptr<Gralloc1::Device> mDevice;
 };
 
 // ---------------------------------------------------------------------------
diff --git a/libs/gui/BufferQueueProducer.cpp b/libs/gui/BufferQueueProducer.cpp
index a540ab9..49552dc 100644
--- a/libs/gui/BufferQueueProducer.cpp
+++ b/libs/gui/BufferQueueProducer.cpp
@@ -1267,7 +1267,10 @@
                     mCore->mSidebandStream.clear();
                     mCore->mDequeueCondition.broadcast();
                     listener = mCore->mConsumerListener;
-                } else if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
+                } else if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
+                    BQ_LOGE("disconnect: not connected (req=%d)", api);
+                    status = NO_INIT;
+                } else {
                     BQ_LOGE("disconnect: still connected to another API "
                             "(cur=%d req=%d)", mCore->mConnectedApi, api);
                     status = BAD_VALUE;
diff --git a/libs/gui/tests/BufferQueue_test.cpp b/libs/gui/tests/BufferQueue_test.cpp
index 893c0a6..60c1277 100644
--- a/libs/gui/tests/BufferQueue_test.cpp
+++ b/libs/gui/tests/BufferQueue_test.cpp
@@ -1181,4 +1181,21 @@
     ASSERT_NE(nullptr, item.mGraphicBuffer.get());
 }
 
+TEST_F(BufferQueueTest, TestProducerConnectDisconnect) {
+    createBufferQueue();
+    sp<DummyConsumer> dc(new DummyConsumer);
+    ASSERT_EQ(OK, mConsumer->consumerConnect(dc, true));
+    IGraphicBufferProducer::QueueBufferOutput output;
+    sp<IProducerListener> dummyListener(new DummyProducerListener);
+    ASSERT_EQ(NO_INIT, mProducer->disconnect(NATIVE_WINDOW_API_CPU));
+    ASSERT_EQ(OK, mProducer->connect(
+            dummyListener, NATIVE_WINDOW_API_CPU, true, &output));
+    ASSERT_EQ(BAD_VALUE, mProducer->connect(
+            dummyListener, NATIVE_WINDOW_API_MEDIA, true, &output));
+
+    ASSERT_EQ(BAD_VALUE, mProducer->disconnect(NATIVE_WINDOW_API_MEDIA));
+    ASSERT_EQ(OK, mProducer->disconnect(NATIVE_WINDOW_API_CPU));
+    ASSERT_EQ(NO_INIT, mProducer->disconnect(NATIVE_WINDOW_API_CPU));
+}
+
 } // namespace android
diff --git a/libs/ui/Android.bp b/libs/ui/Android.bp
index ba37391..5ccf178 100644
--- a/libs/ui/Android.bp
+++ b/libs/ui/Android.bp
@@ -49,8 +49,6 @@
         "Fence.cpp",
         "FenceTime.cpp",
         "FrameStats.cpp",
-        "Gralloc1.cpp",
-        "Gralloc1On0Adapter.cpp",
         "Gralloc2.cpp",
         "GraphicBuffer.cpp",
         "GraphicBufferAllocator.cpp",
diff --git a/libs/ui/Gralloc1.cpp b/libs/ui/Gralloc1.cpp
deleted file mode 100644
index 64a8b40..0000000
--- a/libs/ui/Gralloc1.cpp
+++ /dev/null
@@ -1,511 +0,0 @@
-/*
- * Copyright 2016 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_NDEBUG 0
-
-#include <ui/Gralloc1.h>
-#include <ui/GraphicBuffer.h>
-#include <ui/Gralloc1On0Adapter.h>
-
-#include <vector>
-
-#undef LOG_TAG
-#define LOG_TAG GRALLOC1_LOG_TAG
-
-namespace android {
-
-namespace Gralloc1 {
-
-Descriptor::~Descriptor()
-{
-    int32_t intError = mShimDevice.mFunctions.destroyDescriptor(
-            mShimDevice.mDevice, mDeviceId);
-    auto error = static_cast<gralloc1_error_t>(intError);
-    if (error != GRALLOC1_ERROR_NONE) {
-        ALOGE("destroyDescriptor failed: %d", intError);
-    }
-}
-
-gralloc1_error_t Descriptor::setDimensions(uint32_t width, uint32_t height)
-{
-    int32_t intError = mShimDevice.mFunctions.setDimensions(mShimDevice.mDevice,
-            mDeviceId, width, height);
-    auto error = static_cast<gralloc1_error_t>(intError);
-    if (error != GRALLOC1_ERROR_NONE) {
-        return error;
-    }
-    mWidth = width;
-    mHeight = height;
-    return error;
-}
-
-template <typename ApiType>
-struct Setter {
-    typedef int32_t (*Type)(gralloc1_device_t*, gralloc1_buffer_descriptor_t,
-            ApiType);
-};
-
-template <typename ApiType, typename ValueType>
-static inline gralloc1_error_t setHelper(
-        typename Setter<ApiType>::Type setter, gralloc1_device_t* device,
-        gralloc1_buffer_descriptor_t id, ValueType newValue,
-        ValueType* cacheVariable)
-{
-    int32_t intError = setter(device, id, static_cast<ApiType>(newValue));
-    auto error = static_cast<gralloc1_error_t>(intError);
-    if (error != GRALLOC1_ERROR_NONE) {
-        return error;
-    }
-    *cacheVariable = newValue;
-    return error;
-}
-
-gralloc1_error_t Descriptor::setFormat(android_pixel_format_t format)
-{
-    return setHelper<int32_t>(mShimDevice.mFunctions.setFormat.pfn,
-            mShimDevice.mDevice, mDeviceId, format, &mFormat);
-}
-
-gralloc1_error_t Descriptor::setLayerCount(uint32_t layerCount)
-{
-    if (mShimDevice.hasCapability(GRALLOC1_CAPABILITY_LAYERED_BUFFERS)) {
-        return setHelper<uint32_t>(mShimDevice.mFunctions.setLayerCount.pfn,
-                mShimDevice.mDevice, mDeviceId, layerCount, &mLayerCount);
-    } else {
-        // Layered buffers are not supported on this device.
-        return GRALLOC1_ERROR_UNSUPPORTED;
-    }
-}
-
-gralloc1_error_t Descriptor::setProducerUsage(gralloc1_producer_usage_t usage)
-{
-    return setHelper<uint64_t>(mShimDevice.mFunctions.setProducerUsage.pfn,
-            mShimDevice.mDevice, mDeviceId, usage, &mProducerUsage);
-}
-
-gralloc1_error_t Descriptor::setConsumerUsage(gralloc1_consumer_usage_t usage)
-{
-    return setHelper<uint64_t>(mShimDevice.mFunctions.setConsumerUsage.pfn,
-            mShimDevice.mDevice, mDeviceId, usage, &mConsumerUsage);
-}
-
-Device::Device(gralloc1_device_t* device)
-  : mDevice(device),
-    mCapabilities(loadCapabilities()),
-    mFunctions()
-{
-    if (!loadFunctions()) {
-        ALOGE("Failed to load a required function, aborting");
-        abort();
-    }
-}
-
-bool Device::hasCapability(gralloc1_capability_t capability) const
-{
-    return mCapabilities.count(capability) > 0;
-}
-
-std::string Device::dump()
-{
-    uint32_t length = 0;
-    mFunctions.dump(mDevice, &length, nullptr);
-
-    std::vector<char> output;
-    output.resize(length);
-    mFunctions.dump(mDevice, &length, output.data());
-
-    return std::string(output.cbegin(), output.cend());
-}
-
-std::shared_ptr<Descriptor> Device::createDescriptor()
-{
-    gralloc1_buffer_descriptor_t descriptorId;
-    int32_t intError = mFunctions.createDescriptor(mDevice, &descriptorId);
-    auto error = static_cast<gralloc1_error_t>(intError);
-    if (error != GRALLOC1_ERROR_NONE) {
-        return nullptr;
-    }
-    auto descriptor = std::make_shared<Descriptor>(*this, descriptorId);
-    return descriptor;
-}
-
-static inline bool allocationSucceded(gralloc1_error_t error)
-{
-    return error == GRALLOC1_ERROR_NONE || error == GRALLOC1_ERROR_NOT_SHARED;
-}
-
-gralloc1_error_t Device::allocate(
-        const std::vector<std::shared_ptr<const Descriptor>>& descriptors,
-        std::vector<buffer_handle_t>* outBuffers)
-{
-    if (mFunctions.allocate.pfn == nullptr) {
-        // Allocation is not supported on this device
-        return GRALLOC1_ERROR_UNSUPPORTED;
-    }
-
-    std::vector<gralloc1_buffer_descriptor_t> deviceIds;
-    for (const auto& descriptor : descriptors) {
-        deviceIds.emplace_back(descriptor->getDeviceId());
-    }
-
-    std::vector<buffer_handle_t> buffers(descriptors.size());
-    int32_t intError = mFunctions.allocate(mDevice,
-            static_cast<uint32_t>(descriptors.size()), deviceIds.data(),
-            buffers.data());
-    auto error = static_cast<gralloc1_error_t>(intError);
-    if (allocationSucceded(error)) {
-        *outBuffers = std::move(buffers);
-    }
-
-    return error;
-}
-
-gralloc1_error_t Device::allocate(
-        const std::shared_ptr<const Descriptor>& descriptor,
-        gralloc1_backing_store_t id, buffer_handle_t* outBuffer)
-{
-    gralloc1_error_t error = GRALLOC1_ERROR_NONE;
-
-    if (hasCapability(GRALLOC1_CAPABILITY_ON_ADAPTER)) {
-        buffer_handle_t buffer = nullptr;
-        int32_t intError = mFunctions.allocateWithId(mDevice,
-                descriptor->getDeviceId(), id, &buffer);
-        error = static_cast<gralloc1_error_t>(intError);
-        if (allocationSucceded(error)) {
-            *outBuffer = buffer;
-        }
-    } else {
-        std::vector<std::shared_ptr<const Descriptor>> descriptors;
-        descriptors.emplace_back(descriptor);
-        std::vector<buffer_handle_t> buffers;
-        error = allocate(descriptors, &buffers);
-        if (allocationSucceded(error)) {
-            *outBuffer = buffers[0];
-        }
-    }
-
-    return error;
-}
-
-gralloc1_error_t Device::retain(buffer_handle_t buffer)
-{
-    int32_t intError = mFunctions.retain(mDevice, buffer);
-    return static_cast<gralloc1_error_t>(intError);
-}
-
-gralloc1_error_t Device::retain(const GraphicBuffer* buffer)
-{
-    if (hasCapability(GRALLOC1_CAPABILITY_ON_ADAPTER)) {
-        return mFunctions.retainGraphicBuffer(mDevice, buffer);
-    } else {
-        return retain(buffer->getNativeBuffer()->handle);
-    }
-}
-
-gralloc1_error_t Device::release(buffer_handle_t buffer)
-{
-    int32_t intError = mFunctions.release(mDevice, buffer);
-    return static_cast<gralloc1_error_t>(intError);
-}
-
-gralloc1_error_t Device::getDimensions(buffer_handle_t buffer,
-        uint32_t* outWidth, uint32_t* outHeight)
-{
-    uint32_t width = 0;
-    uint32_t height = 0;
-    int32_t intError = mFunctions.getDimensions(mDevice, buffer, &width,
-            &height);
-    auto error = static_cast<gralloc1_error_t>(intError);
-    if (error == GRALLOC1_ERROR_NONE) {
-        *outWidth = width;
-        *outHeight = height;
-    }
-    return error;
-}
-
-gralloc1_error_t Device::getFormat(buffer_handle_t buffer,
-        int32_t* outFormat)
-{
-    int32_t format = 0;
-    int32_t intError = mFunctions.getFormat(mDevice, buffer, &format);
-    auto error = static_cast<gralloc1_error_t>(intError);
-    if (error == GRALLOC1_ERROR_NONE) {
-        *outFormat = format;
-    }
-    return error;
-}
-
-gralloc1_error_t Device::getLayerCount(buffer_handle_t buffer,
-        uint32_t* outLayerCount)
-{
-    if (hasCapability(GRALLOC1_CAPABILITY_LAYERED_BUFFERS)) {
-        uint32_t layerCount = 0;
-        int32_t intError = mFunctions.getLayerCount(mDevice, buffer,
-                &layerCount);
-        auto error = static_cast<gralloc1_error_t>(intError);
-        if (error == GRALLOC1_ERROR_NONE) {
-            *outLayerCount = layerCount;
-        }
-        return error;
-    } else {
-        // Layered buffers are not supported on this device.
-        return GRALLOC1_ERROR_UNSUPPORTED;
-    }
-}
-
-gralloc1_error_t Device::getProducerUsage(buffer_handle_t buffer,
-        uint64_t* outProducerUsage)
-{
-    uint64_t usage = 0;
-    int32_t intError = mFunctions.getProducerUsage(mDevice, buffer, &usage);
-    auto error = static_cast<gralloc1_error_t>(intError);
-    if (error == GRALLOC1_ERROR_NONE) {
-        *outProducerUsage = usage;
-    }
-    return error;
-}
-
-gralloc1_error_t Device::getConsumerUsage(buffer_handle_t buffer,
-        uint64_t* outConsumerUsage)
-{
-    uint64_t usage = 0;
-    int32_t intError = mFunctions.getConsumerUsage(mDevice, buffer, &usage);
-    auto error = static_cast<gralloc1_error_t>(intError);
-    if (error == GRALLOC1_ERROR_NONE) {
-        *outConsumerUsage = usage;
-    }
-    return error;
-}
-
-gralloc1_error_t Device::getBackingStore(buffer_handle_t buffer,
-        uint64_t* outBackingStore)
-{
-    uint64_t store = 0;
-    int32_t intError = mFunctions.getBackingStore(mDevice, buffer, &store);
-    auto error = static_cast<gralloc1_error_t>(intError);
-    if (error == GRALLOC1_ERROR_NONE) {
-        *outBackingStore = store;
-    }
-    return error;
-}
-
-gralloc1_error_t Device::getStride(buffer_handle_t buffer,
-        uint32_t* outStride)
-{
-    uint32_t stride = 0;
-    int32_t intError = mFunctions.getStride(mDevice, buffer, &stride);
-    auto error = static_cast<gralloc1_error_t>(intError);
-    if (error == GRALLOC1_ERROR_NONE) {
-        *outStride = stride;
-    }
-    return error;
-}
-
-gralloc1_error_t Device::getNumFlexPlanes(buffer_handle_t buffer,
-        uint32_t* outNumPlanes)
-{
-    uint32_t numPlanes = 0;
-    int32_t intError = mFunctions.getNumFlexPlanes(mDevice, buffer, &numPlanes);
-    auto error = static_cast<gralloc1_error_t>(intError);
-    if (error == GRALLOC1_ERROR_NONE) {
-        *outNumPlanes = numPlanes;
-    }
-    return error;
-}
-
-gralloc1_error_t Device::lock(buffer_handle_t buffer,
-        gralloc1_producer_usage_t producerUsage,
-        gralloc1_consumer_usage_t consumerUsage,
-        const gralloc1_rect_t* accessRegion, void** outData,
-        const sp<Fence>& acquireFence)
-{
-    ALOGV("Calling lock(%p)", buffer);
-    return lockHelper(mFunctions.lock, buffer, producerUsage,
-            consumerUsage, accessRegion, outData, acquireFence);
-}
-
-gralloc1_error_t Device::lockFlex(buffer_handle_t buffer,
-        gralloc1_producer_usage_t producerUsage,
-        gralloc1_consumer_usage_t consumerUsage,
-        const gralloc1_rect_t* accessRegion,
-        struct android_flex_layout* outData,
-        const sp<Fence>& acquireFence)
-{
-    ALOGV("Calling lockFlex(%p)", buffer);
-    return lockHelper(mFunctions.lockFlex, buffer, producerUsage,
-            consumerUsage, accessRegion, outData, acquireFence);
-}
-
-gralloc1_error_t Device::lockYCbCr(buffer_handle_t buffer,
-        gralloc1_producer_usage_t producerUsage,
-        gralloc1_consumer_usage_t consumerUsage,
-        const gralloc1_rect_t* accessRegion,
-        struct android_ycbcr* outData,
-        const sp<Fence>& acquireFence)
-{
-    ALOGV("Calling lockYCbCr(%p)", buffer);
-    return lockHelper(mFunctions.lockYCbCr, buffer, producerUsage,
-            consumerUsage, accessRegion, outData, acquireFence);
-}
-
-gralloc1_error_t Device::unlock(buffer_handle_t buffer, sp<Fence>* outFence)
-{
-    int32_t fenceFd = -1;
-    int32_t intError = mFunctions.unlock(mDevice, buffer, &fenceFd);
-    auto error = static_cast<gralloc1_error_t>(intError);
-    if (error == GRALLOC1_ERROR_NONE) {
-        *outFence = new Fence(fenceFd);
-    }
-    return error;
-}
-
-std::unordered_set<gralloc1_capability_t> Device::loadCapabilities()
-{
-    std::vector<int32_t> intCapabilities;
-    uint32_t numCapabilities = 0;
-    mDevice->getCapabilities(mDevice, &numCapabilities, nullptr);
-
-    intCapabilities.resize(numCapabilities);
-    mDevice->getCapabilities(mDevice, &numCapabilities, intCapabilities.data());
-
-    std::unordered_set<gralloc1_capability_t> capabilities;
-    for (const auto intCapability : intCapabilities) {
-        capabilities.emplace(static_cast<gralloc1_capability_t>(intCapability));
-    }
-    return capabilities;
-}
-
-bool Device::loadFunctions()
-{
-    // Functions which must always be present
-    if (!mFunctions.dump.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.createDescriptor.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.destroyDescriptor.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.setConsumerUsage.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.setDimensions.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.setFormat.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.setProducerUsage.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.getBackingStore.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.getConsumerUsage.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.getDimensions.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.getFormat.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.getProducerUsage.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.getStride.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.retain.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.release.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.getNumFlexPlanes.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.lock.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.lockFlex.load(mDevice, true)) {
-        return false;
-    }
-    if (!mFunctions.unlock.load(mDevice, true)) {
-        return false;
-    }
-
-    if (hasCapability(GRALLOC1_CAPABILITY_ON_ADAPTER)) {
-        // These should always be present on the adapter
-        if (!mFunctions.retainGraphicBuffer.load(mDevice, true)) {
-            return false;
-        }
-        if (!mFunctions.lockYCbCr.load(mDevice, true)) {
-            return false;
-        }
-
-        // allocateWithId may not be present if we're only able to map in this
-        // process
-        mFunctions.allocateWithId.load(mDevice, false);
-    } else {
-        // allocate may not be present if we're only able to map in this process
-        mFunctions.allocate.load(mDevice, false);
-    }
-
-    if (hasCapability(GRALLOC1_CAPABILITY_LAYERED_BUFFERS)) {
-        if (!mFunctions.setLayerCount.load(mDevice, true)) {
-            return false;
-        }
-        if (!mFunctions.getLayerCount.load(mDevice, true)) {
-            return false;
-        }
-    }
-
-    return true;
-}
-
-std::unique_ptr<Gralloc1On0Adapter> Loader::mAdapter = nullptr;
-
-Loader::Loader()
-  : mDevice(nullptr)
-{
-    hw_module_t const* module;
-    int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module);
-    uint8_t majorVersion = (module->module_api_version >> 8) & 0xFF;
-    uint8_t minorVersion = module->module_api_version & 0xFF;
-    gralloc1_device_t* device = nullptr;
-    if (majorVersion == 1) {
-        gralloc1_open(module, &device);
-    } else {
-        if (!mAdapter) {
-            mAdapter = std::make_unique<Gralloc1On0Adapter>(module);
-        }
-        device = mAdapter->getDevice();
-    }
-    mDevice = std::make_unique<Gralloc1::Device>(device);
-}
-
-Loader::~Loader() {}
-
-std::unique_ptr<Device> Loader::getDevice()
-{
-    return std::move(mDevice);
-}
-
-} // namespace android::Gralloc1
-
-} // namespace android
diff --git a/libs/ui/Gralloc1On0Adapter.cpp b/libs/ui/Gralloc1On0Adapter.cpp
deleted file mode 100644
index 9ee9838..0000000
--- a/libs/ui/Gralloc1On0Adapter.cpp
+++ /dev/null
@@ -1,501 +0,0 @@
-/*
- * Copyright 2016 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.
- */
-
-#undef LOG_TAG
-#define LOG_TAG "Gralloc1On0Adapter"
-//#define LOG_NDEBUG 0
-
-#include <ui/Gralloc1On0Adapter.h>
-
-#include <algorithm>
-#include <array>
-
-#include <grallocusage/GrallocUsageConversion.h>
-
-#include <hardware/gralloc.h>
-
-#include <ui/GraphicBuffer.h>
-#include <ui/Gralloc1.h>
-
-#include <utils/Log.h>
-
-#include <inttypes.h>
-
-template <typename PFN, typename T>
-static gralloc1_function_pointer_t asFP(T function)
-{
-    static_assert(std::is_same<PFN, T>::value, "Incompatible function pointer");
-    return reinterpret_cast<gralloc1_function_pointer_t>(function);
-}
-
-namespace android {
-
-Gralloc1On0Adapter::Gralloc1On0Adapter(const hw_module_t* module)
-  : mModule(reinterpret_cast<const gralloc_module_t*>(module)),
-    mMinorVersion(mModule->common.module_api_version & 0xFF),
-    mDevice(nullptr)
-{
-    ALOGV("Constructing");
-    getCapabilities = getCapabilitiesHook;
-    getFunction = getFunctionHook;
-    int error = ::gralloc_open(&(mModule->common), &mDevice);
-    if (error) {
-        ALOGE("Failed to open gralloc0 module: %d", error);
-    }
-    ALOGV("Opened gralloc0 device %p", mDevice);
-}
-
-Gralloc1On0Adapter::~Gralloc1On0Adapter()
-{
-    ALOGV("Destructing");
-    if (mDevice) {
-        ALOGV("Closing gralloc0 device %p", mDevice);
-        ::gralloc_close(mDevice);
-    }
-}
-
-void Gralloc1On0Adapter::doGetCapabilities(uint32_t* outCount,
-        int32_t* outCapabilities)
-{
-    constexpr std::array<int32_t, 2> supportedCapabilities = {{
-        GRALLOC1_CAPABILITY_ON_ADAPTER,
-        GRALLOC1_CAPABILITY_RELEASE_IMPLY_DELETE,
-    }};
-
-    if (outCapabilities == nullptr) {
-        *outCount = supportedCapabilities.size();
-    } else {
-        *outCount = std::min(*outCount, static_cast<uint32_t>(
-                    supportedCapabilities.size()));
-        std::copy_n(supportedCapabilities.begin(),
-                *outCount, outCapabilities);
-    }
-}
-
-gralloc1_function_pointer_t Gralloc1On0Adapter::doGetFunction(
-        int32_t intDescriptor)
-{
-    constexpr auto lastDescriptor =
-            static_cast<int32_t>(GRALLOC1_LAST_ADAPTER_FUNCTION);
-    if (intDescriptor < 0 || intDescriptor > lastDescriptor) {
-        ALOGE("Invalid function descriptor");
-        return nullptr;
-    }
-
-    auto descriptor =
-            static_cast<gralloc1_function_descriptor_t>(intDescriptor);
-    switch (descriptor) {
-        case GRALLOC1_FUNCTION_DUMP:
-            return asFP<GRALLOC1_PFN_DUMP>(dumpHook);
-        case GRALLOC1_FUNCTION_CREATE_DESCRIPTOR:
-            return asFP<GRALLOC1_PFN_CREATE_DESCRIPTOR>(createDescriptorHook);
-        case GRALLOC1_FUNCTION_DESTROY_DESCRIPTOR:
-            return asFP<GRALLOC1_PFN_DESTROY_DESCRIPTOR>(destroyDescriptorHook);
-        case GRALLOC1_FUNCTION_SET_CONSUMER_USAGE:
-            return asFP<GRALLOC1_PFN_SET_CONSUMER_USAGE>(setConsumerUsageHook);
-        case GRALLOC1_FUNCTION_SET_DIMENSIONS:
-            return asFP<GRALLOC1_PFN_SET_DIMENSIONS>(setDimensionsHook);
-        case GRALLOC1_FUNCTION_SET_FORMAT:
-            return asFP<GRALLOC1_PFN_SET_FORMAT>(setFormatHook);
-        case GRALLOC1_FUNCTION_SET_LAYER_COUNT:
-            return asFP<GRALLOC1_PFN_SET_LAYER_COUNT>(setLayerCountHook);
-        case GRALLOC1_FUNCTION_SET_PRODUCER_USAGE:
-            return asFP<GRALLOC1_PFN_SET_PRODUCER_USAGE>(setProducerUsageHook);
-        case GRALLOC1_FUNCTION_GET_BACKING_STORE:
-            return asFP<GRALLOC1_PFN_GET_BACKING_STORE>(
-                    bufferHook<decltype(&Buffer::getBackingStore),
-                    &Buffer::getBackingStore, gralloc1_backing_store_t*>);
-        case GRALLOC1_FUNCTION_GET_CONSUMER_USAGE:
-            return asFP<GRALLOC1_PFN_GET_CONSUMER_USAGE>(getConsumerUsageHook);
-        case GRALLOC1_FUNCTION_GET_DIMENSIONS:
-            return asFP<GRALLOC1_PFN_GET_DIMENSIONS>(
-                    bufferHook<decltype(&Buffer::getDimensions),
-                    &Buffer::getDimensions, uint32_t*, uint32_t*>);
-        case GRALLOC1_FUNCTION_GET_FORMAT:
-            return asFP<GRALLOC1_PFN_GET_FORMAT>(
-                    bufferHook<decltype(&Buffer::getFormat),
-                    &Buffer::getFormat, int32_t*>);
-        case GRALLOC1_FUNCTION_GET_LAYER_COUNT:
-            return asFP<GRALLOC1_PFN_GET_LAYER_COUNT>(
-                    bufferHook<decltype(&Buffer::getLayerCount),
-                    &Buffer::getLayerCount, uint32_t*>);
-        case GRALLOC1_FUNCTION_GET_PRODUCER_USAGE:
-            return asFP<GRALLOC1_PFN_GET_PRODUCER_USAGE>(getProducerUsageHook);
-        case GRALLOC1_FUNCTION_GET_STRIDE:
-            return asFP<GRALLOC1_PFN_GET_STRIDE>(
-                    bufferHook<decltype(&Buffer::getStride),
-                    &Buffer::getStride, uint32_t*>);
-        case GRALLOC1_FUNCTION_ALLOCATE:
-            // Not provided, since we'll use ALLOCATE_WITH_ID
-            return nullptr;
-        case GRALLOC1_FUNCTION_ALLOCATE_WITH_ID:
-            if (mDevice != nullptr) {
-                return asFP<GRALLOC1_PFN_ALLOCATE_WITH_ID>(allocateWithIdHook);
-            } else {
-                return nullptr;
-            }
-        case GRALLOC1_FUNCTION_RETAIN:
-            return asFP<GRALLOC1_PFN_RETAIN>(
-                    managementHook<&Gralloc1On0Adapter::retain>);
-        case GRALLOC1_FUNCTION_RELEASE:
-            return asFP<GRALLOC1_PFN_RELEASE>(
-                    managementHook<&Gralloc1On0Adapter::release>);
-        case GRALLOC1_FUNCTION_RETAIN_GRAPHIC_BUFFER:
-            return asFP<GRALLOC1_PFN_RETAIN_GRAPHIC_BUFFER>(
-                    retainGraphicBufferHook);
-        case GRALLOC1_FUNCTION_GET_NUM_FLEX_PLANES:
-            return asFP<GRALLOC1_PFN_GET_NUM_FLEX_PLANES>(
-                    bufferHook<decltype(&Buffer::getNumFlexPlanes),
-                    &Buffer::getNumFlexPlanes, uint32_t*>);
-        case GRALLOC1_FUNCTION_LOCK:
-            return asFP<GRALLOC1_PFN_LOCK>(
-                    lockHook<void*, &Gralloc1On0Adapter::lock>);
-        case GRALLOC1_FUNCTION_LOCK_FLEX:
-            return asFP<GRALLOC1_PFN_LOCK_FLEX>(
-                    lockHook<struct android_flex_layout,
-                    &Gralloc1On0Adapter::lockFlex>);
-        case GRALLOC1_FUNCTION_LOCK_YCBCR:
-            return asFP<GRALLOC1_PFN_LOCK_YCBCR>(
-                    lockHook<struct android_ycbcr,
-                    &Gralloc1On0Adapter::lockYCbCr>);
-        case GRALLOC1_FUNCTION_UNLOCK:
-            return asFP<GRALLOC1_PFN_UNLOCK>(unlockHook);
-        case GRALLOC1_FUNCTION_INVALID:
-            ALOGE("Invalid function descriptor");
-            return nullptr;
-    }
-
-    ALOGE("Unknown function descriptor: %d", intDescriptor);
-    return nullptr;
-}
-
-void Gralloc1On0Adapter::dump(uint32_t* outSize, char* outBuffer)
-{
-    ALOGV("dump(%u (%p), %p", outSize ? *outSize : 0, outSize, outBuffer);
-
-    if (!mDevice->dump) {
-        // dump is optional on gralloc0 implementations
-        *outSize = 0;
-        return;
-    }
-
-    if (!outBuffer) {
-        constexpr int32_t BUFFER_LENGTH = 4096;
-        char buffer[BUFFER_LENGTH] = {};
-        mDevice->dump(mDevice, buffer, BUFFER_LENGTH);
-        buffer[BUFFER_LENGTH - 1] = 0; // Ensure the buffer is null-terminated
-        size_t actualLength = std::strlen(buffer);
-        mCachedDump.resize(actualLength);
-        std::copy_n(buffer, actualLength, mCachedDump.begin());
-        *outSize = static_cast<uint32_t>(actualLength);
-    } else {
-        *outSize = std::min(*outSize,
-                static_cast<uint32_t>(mCachedDump.size()));
-        outBuffer = std::copy_n(mCachedDump.cbegin(), *outSize, outBuffer);
-    }
-}
-
-gralloc1_error_t Gralloc1On0Adapter::createDescriptor(
-        gralloc1_buffer_descriptor_t* outDescriptor)
-{
-    auto descriptorId = sNextBufferDescriptorId++;
-    std::lock_guard<std::mutex> lock(mDescriptorMutex);
-    mDescriptors.emplace(descriptorId,
-            std::make_shared<Descriptor>(this, descriptorId));
-
-    ALOGV("Created descriptor %" PRIu64, descriptorId);
-
-    *outDescriptor = descriptorId;
-    return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t Gralloc1On0Adapter::destroyDescriptor(
-        gralloc1_buffer_descriptor_t descriptor)
-{
-    ALOGV("Destroying descriptor %" PRIu64, descriptor);
-
-    std::lock_guard<std::mutex> lock(mDescriptorMutex);
-    if (mDescriptors.count(descriptor) == 0) {
-        return GRALLOC1_ERROR_BAD_DESCRIPTOR;
-    }
-
-    mDescriptors.erase(descriptor);
-    return GRALLOC1_ERROR_NONE;
-}
-
-Gralloc1On0Adapter::Buffer::Buffer(buffer_handle_t handle,
-        gralloc1_backing_store_t store, const Descriptor& descriptor,
-        uint32_t stride, bool wasAllocated)
-  : mHandle(handle),
-    mReferenceCount(1),
-    mStore(store),
-    mDescriptor(descriptor),
-    mStride(stride),
-    mWasAllocated(wasAllocated) {}
-
-gralloc1_error_t Gralloc1On0Adapter::allocate(
-        const std::shared_ptr<Descriptor>& descriptor,
-        gralloc1_backing_store_t store,
-        buffer_handle_t* outBufferHandle)
-{
-    ALOGV("allocate(%" PRIu64 ", %#" PRIx64 ")", descriptor->id, store);
-
-    // If this function is being called, it's because we handed out its function
-    // pointer, which only occurs when mDevice has been loaded successfully and
-    // we are permitted to allocate
-
-    int usage = android_convertGralloc1To0Usage(descriptor->producerUsage,
-            descriptor->consumerUsage);
-    buffer_handle_t handle = nullptr;
-    int stride = 0;
-    ALOGV("Calling alloc(%p, %u, %u, %i, %u)", mDevice, descriptor->width,
-            descriptor->height, descriptor->format, usage);
-    auto error = mDevice->alloc(mDevice,
-            static_cast<int>(descriptor->width),
-            static_cast<int>(descriptor->height), descriptor->format,
-            usage, &handle, &stride);
-    if (error != 0) {
-        ALOGE("gralloc0 allocation failed: %d (%s)", error,
-                strerror(-error));
-        return GRALLOC1_ERROR_NO_RESOURCES;
-    }
-
-    *outBufferHandle = handle;
-    auto buffer = std::make_shared<Buffer>(handle, store, *descriptor, stride,
-            true);
-
-    std::lock_guard<std::mutex> lock(mBufferMutex);
-    mBuffers.emplace(handle, std::move(buffer));
-
-    return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t Gralloc1On0Adapter::allocateWithIdHook(
-        gralloc1_device_t* device, gralloc1_buffer_descriptor_t descriptorId,
-        gralloc1_backing_store_t store, buffer_handle_t* outBuffer)
-{
-    auto adapter = getAdapter(device);
-
-    auto descriptor = adapter->getDescriptor(descriptorId);
-    if (!descriptor) {
-        return GRALLOC1_ERROR_BAD_DESCRIPTOR;
-    }
-
-    buffer_handle_t bufferHandle = nullptr;
-    auto error = adapter->allocate(descriptor, store, &bufferHandle);
-    if (error != GRALLOC1_ERROR_NONE) {
-        return error;
-    }
-
-    *outBuffer = bufferHandle;
-    return error;
-}
-
-gralloc1_error_t Gralloc1On0Adapter::retain(
-        const std::shared_ptr<Buffer>& buffer)
-{
-    std::lock_guard<std::mutex> lock(mBufferMutex);
-    buffer->retain();
-    return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t Gralloc1On0Adapter::release(
-        const std::shared_ptr<Buffer>& buffer)
-{
-    std::lock_guard<std::mutex> lock(mBufferMutex);
-    if (!buffer->release()) {
-        return GRALLOC1_ERROR_NONE;
-    }
-
-    buffer_handle_t handle = buffer->getHandle();
-    if (buffer->wasAllocated()) {
-        ALOGV("Calling free(%p)", handle);
-        int result = mDevice->free(mDevice, handle);
-        if (result != 0) {
-            ALOGE("gralloc0 free failed: %d", result);
-        }
-    } else {
-        ALOGV("Calling unregisterBuffer(%p)", handle);
-        int result = mModule->unregisterBuffer(mModule, handle);
-        if (result != 0) {
-            ALOGE("gralloc0 unregister failed: %d", result);
-        }
-
-        native_handle_close(handle);
-        native_handle_delete(const_cast<native_handle_t*>(handle));
-    }
-
-    mBuffers.erase(handle);
-    return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t Gralloc1On0Adapter::retain(
-        const android::GraphicBuffer* graphicBuffer)
-{
-    ALOGV("retainGraphicBuffer(%p, %#" PRIx64 ")",
-            graphicBuffer->getNativeBuffer()->handle, graphicBuffer->getId());
-
-    buffer_handle_t handle = graphicBuffer->getNativeBuffer()->handle;
-    std::lock_guard<std::mutex> lock(mBufferMutex);
-    if (mBuffers.count(handle) != 0) {
-        mBuffers[handle]->retain();
-        return GRALLOC1_ERROR_NONE;
-    }
-
-    ALOGV("Calling registerBuffer(%p)", handle);
-    int result = mModule->registerBuffer(mModule, handle);
-    if (result != 0) {
-        ALOGE("gralloc0 register failed: %d", result);
-        return GRALLOC1_ERROR_NO_RESOURCES;
-    }
-
-    Descriptor descriptor{this, sNextBufferDescriptorId++};
-    descriptor.setDimensions(graphicBuffer->getWidth(),
-            graphicBuffer->getHeight());
-    descriptor.setFormat(graphicBuffer->getPixelFormat());
-    descriptor.setProducerUsage(
-            static_cast<gralloc1_producer_usage_t>(graphicBuffer->getUsage()));
-    descriptor.setConsumerUsage(
-            static_cast<gralloc1_consumer_usage_t>(graphicBuffer->getUsage()));
-    auto buffer = std::make_shared<Buffer>(handle,
-            static_cast<gralloc1_backing_store_t>(graphicBuffer->getId()),
-            descriptor, graphicBuffer->getStride(), false);
-    mBuffers.emplace(handle, std::move(buffer));
-    return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t Gralloc1On0Adapter::lock(
-        const std::shared_ptr<Buffer>& buffer,
-        gralloc1_producer_usage_t producerUsage,
-        gralloc1_consumer_usage_t consumerUsage,
-        const gralloc1_rect_t& accessRegion, void** outData,
-        const sp<Fence>& acquireFence)
-{
-    if (mMinorVersion >= 3) {
-        int result = mModule->lockAsync(mModule, buffer->getHandle(),
-                android_convertGralloc1To0Usage(producerUsage, consumerUsage),
-                accessRegion.left, accessRegion.top, accessRegion.width,
-                accessRegion.height, outData, acquireFence->dup());
-        if (result != 0) {
-            return GRALLOC1_ERROR_UNSUPPORTED;
-        }
-    } else {
-        acquireFence->waitForever("Gralloc1On0Adapter::lock");
-        int result = mModule->lock(mModule, buffer->getHandle(),
-                android_convertGralloc1To0Usage(producerUsage, consumerUsage),
-                accessRegion.left, accessRegion.top, accessRegion.width,
-                accessRegion.height, outData);
-        ALOGV("gralloc0 lock returned %d", result);
-        if (result != 0) {
-            return GRALLOC1_ERROR_UNSUPPORTED;
-        }
-    }
-    return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t Gralloc1On0Adapter::lockFlex(
-        const std::shared_ptr<Buffer>& /*buffer*/,
-        gralloc1_producer_usage_t /*producerUsage*/,
-        gralloc1_consumer_usage_t /*consumerUsage*/,
-        const gralloc1_rect_t& /*accessRegion*/,
-        struct android_flex_layout* /*outData*/,
-        const sp<Fence>& /*acquireFence*/)
-{
-    // TODO
-    return GRALLOC1_ERROR_UNSUPPORTED;
-}
-
-gralloc1_error_t Gralloc1On0Adapter::lockYCbCr(
-        const std::shared_ptr<Buffer>& buffer,
-        gralloc1_producer_usage_t producerUsage,
-        gralloc1_consumer_usage_t consumerUsage,
-        const gralloc1_rect_t& accessRegion, struct android_ycbcr* outData,
-        const sp<Fence>& acquireFence)
-{
-    if (mMinorVersion >= 3 && mModule->lockAsync_ycbcr) {
-        int result = mModule->lockAsync_ycbcr(mModule, buffer->getHandle(),
-                android_convertGralloc1To0Usage(producerUsage, consumerUsage),
-                accessRegion.left, accessRegion.top, accessRegion.width,
-                accessRegion.height, outData, acquireFence->dup());
-        if (result != 0) {
-            return GRALLOC1_ERROR_UNSUPPORTED;
-        }
-    } else if (mModule->lock_ycbcr) {
-        acquireFence->waitForever("Gralloc1On0Adapter::lockYCbCr");
-        int result = mModule->lock_ycbcr(mModule, buffer->getHandle(),
-                android_convertGralloc1To0Usage(producerUsage, consumerUsage),
-                accessRegion.left, accessRegion.top, accessRegion.width,
-                accessRegion.height, outData);
-        ALOGV("gralloc0 lockYCbCr returned %d", result);
-        if (result != 0) {
-            return GRALLOC1_ERROR_UNSUPPORTED;
-        }
-    } else {
-        return GRALLOC1_ERROR_UNSUPPORTED;
-    }
-
-    return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t Gralloc1On0Adapter::unlock(
-        const std::shared_ptr<Buffer>& buffer,
-        sp<Fence>* outReleaseFence)
-{
-    if (mMinorVersion >= 3) {
-        int fenceFd = -1;
-        int result = mModule->unlockAsync(mModule, buffer->getHandle(),
-                &fenceFd);
-        if (result != 0) {
-            close(fenceFd);
-            ALOGE("gralloc0 unlockAsync failed: %d", result);
-        } else {
-            *outReleaseFence = new Fence(fenceFd);
-        }
-    } else {
-        int result = mModule->unlock(mModule, buffer->getHandle());
-        if (result != 0) {
-            ALOGE("gralloc0 unlock failed: %d", result);
-        }
-    }
-    return GRALLOC1_ERROR_NONE;
-}
-
-std::shared_ptr<Gralloc1On0Adapter::Descriptor>
-Gralloc1On0Adapter::getDescriptor(gralloc1_buffer_descriptor_t descriptorId)
-{
-    std::lock_guard<std::mutex> lock(mDescriptorMutex);
-    if (mDescriptors.count(descriptorId) == 0) {
-        return nullptr;
-    }
-
-    return mDescriptors[descriptorId];
-}
-
-std::shared_ptr<Gralloc1On0Adapter::Buffer> Gralloc1On0Adapter::getBuffer(
-        buffer_handle_t bufferHandle)
-{
-    std::lock_guard<std::mutex> lock(mBufferMutex);
-    if (mBuffers.count(bufferHandle) == 0) {
-        return nullptr;
-    }
-
-    return mBuffers[bufferHandle];
-}
-
-std::atomic<gralloc1_buffer_descriptor_t>
-        Gralloc1On0Adapter::sNextBufferDescriptorId(1);
-
-} // namespace android
diff --git a/libs/ui/Gralloc2.cpp b/libs/ui/Gralloc2.cpp
index 75f5686..f8d9401 100644
--- a/libs/ui/Gralloc2.cpp
+++ b/libs/ui/Gralloc2.cpp
@@ -33,7 +33,7 @@
 Mapper::Mapper()
 {
     mMapper = IMapper::getService();
-    if (mMapper != nullptr && mMapper->isRemote()) {
+    if (mMapper == nullptr || mMapper->isRemote()) {
         LOG_ALWAYS_FATAL("gralloc-mapper must be in passthrough mode");
     }
 }
@@ -196,8 +196,9 @@
 Allocator::Allocator(const Mapper& mapper)
     : mMapper(mapper)
 {
-    if (mMapper.valid()) {
-        mAllocator = IAllocator::getService();
+    mAllocator = IAllocator::getService();
+    if (mAllocator == nullptr) {
+        LOG_ALWAYS_FATAL("gralloc-alloc is missing");
     }
 }
 
diff --git a/libs/ui/GraphicBuffer.cpp b/libs/ui/GraphicBuffer.cpp
index eb5c7b6..b0cb012 100644
--- a/libs/ui/GraphicBuffer.cpp
+++ b/libs/ui/GraphicBuffer.cpp
@@ -188,18 +188,6 @@
         uint64_t producerUsage, uint64_t consumerUsage,
         uint32_t stride)
 {
-    native_handle_t* clone = nullptr;
-
-    if (method == CLONE_HANDLE) {
-        clone = native_handle_clone(handle);
-        if (!clone) {
-            return NO_MEMORY;
-        }
-
-        handle = clone;
-        method = TAKE_UNREGISTERED_HANDLE;
-    }
-
     ANativeWindowBuffer::width  = static_cast<int>(width);
     ANativeWindowBuffer::height = static_cast<int>(height);
     ANativeWindowBuffer::stride = static_cast<int>(stride);
@@ -208,25 +196,28 @@
         android_convertGralloc1To0Usage(producerUsage, consumerUsage);
 
     ANativeWindowBuffer::layerCount = layerCount;
-    ANativeWindowBuffer::handle = handle;
 
     mOwner = (method == WRAP_HANDLE) ? ownNone : ownHandle;
 
-    if (method == TAKE_UNREGISTERED_HANDLE) {
-        status_t err = mBufferMapper.importBuffer(this);
+    if (method == TAKE_UNREGISTERED_HANDLE || method == CLONE_HANDLE) {
+        buffer_handle_t importedHandle;
+        status_t err = mBufferMapper.importBuffer(handle, &importedHandle);
         if (err != NO_ERROR) {
-            // clean up cloned handle
-            if (clone) {
-                native_handle_close(clone);
-                native_handle_delete(clone);
-            }
-
             initWithHandle(nullptr, WRAP_HANDLE, 0, 0, 0, 0, 0, 0, 0);
 
             return err;
         }
+
+        if (method == TAKE_UNREGISTERED_HANDLE) {
+            native_handle_close(handle);
+            native_handle_delete(const_cast<native_handle_t*>(handle));
+        }
+
+        handle = importedHandle;
     }
 
+    ANativeWindowBuffer::handle = handle;
+
     return NO_ERROR;
 }
 
@@ -447,7 +438,8 @@
     mOwner = ownHandle;
 
     if (handle != 0) {
-        status_t err = mBufferMapper.importBuffer(this);
+        buffer_handle_t importedHandle;
+        status_t err = mBufferMapper.importBuffer(handle, &importedHandle);
         if (err != NO_ERROR) {
             width = height = stride = format = layerCount = usage = 0;
             handle = NULL;
@@ -455,6 +447,10 @@
                     strerror(-err), err);
             return err;
         }
+
+        native_handle_close(handle);
+        native_handle_delete(const_cast<native_handle_t*>(handle));
+        handle = importedHandle;
     }
 
     buffer = static_cast<void const*>(static_cast<uint8_t const*>(buffer) + sizeNeeded);
diff --git a/libs/ui/GraphicBufferAllocator.cpp b/libs/ui/GraphicBufferAllocator.cpp
index 1f6c537..9beed0e 100644
--- a/libs/ui/GraphicBufferAllocator.cpp
+++ b/libs/ui/GraphicBufferAllocator.cpp
@@ -46,10 +46,6 @@
     mAllocator(std::make_unique<Gralloc2::Allocator>(
                 mMapper.getGrallocMapper()))
 {
-    if (!mAllocator->valid()) {
-        mLoader = std::make_unique<Gralloc1::Loader>();
-        mDevice = mLoader->getDevice();
-    }
 }
 
 GraphicBufferAllocator::~GraphicBufferAllocator() {}
@@ -87,13 +83,7 @@
     snprintf(buffer, SIZE, "Total allocated (estimate): %.2f KB\n", total/1024.0);
     result.append(buffer);
 
-    std::string deviceDump;
-    if (mAllocator->valid()) {
-        deviceDump = mAllocator->dumpDebugInfo();
-    } else {
-        deviceDump = mDevice->dump();
-    }
-
+    std::string deviceDump = mAllocator->dumpDebugInfo();
     result.append(deviceDump.c_str(), deviceDump.size());
 }
 
@@ -107,7 +97,7 @@
 status_t GraphicBufferAllocator::allocate(uint32_t width, uint32_t height,
         PixelFormat format, uint32_t layerCount, uint64_t producerUsage,
         uint64_t consumerUsage, buffer_handle_t* handle, uint32_t* stride,
-        uint64_t graphicBufferId, std::string requestorName)
+        uint64_t /*graphicBufferId*/, std::string requestorName)
 {
     ATRACE_CALL();
 
@@ -120,76 +110,16 @@
     if (layerCount < 1)
         layerCount = 1;
 
-    gralloc1_error_t error;
-    if (mAllocator->valid()) {
-        Gralloc2::IMapper::BufferDescriptorInfo info = {};
-        info.width = width;
-        info.height = height;
-        info.layerCount = layerCount;
-        info.format = static_cast<Gralloc2::PixelFormat>(format);
-        info.usage = static_cast<uint64_t>(android_convertGralloc1To0Usage(
+    Gralloc2::IMapper::BufferDescriptorInfo info = {};
+    info.width = width;
+    info.height = height;
+    info.layerCount = layerCount;
+    info.format = static_cast<Gralloc2::PixelFormat>(format);
+    info.usage = static_cast<uint64_t>(android_convertGralloc1To0Usage(
                 producerUsage, consumerUsage));
-        error = static_cast<gralloc1_error_t>(mAllocator->allocate(info,
-                    stride, handle));
-        if (error != GRALLOC1_ERROR_NONE) {
-            return NO_MEMORY;
-        }
-    } else {
-        auto descriptor = mDevice->createDescriptor();
-        error = descriptor->setDimensions(width, height);
-        if (error != GRALLOC1_ERROR_NONE) {
-            ALOGE("Failed to set dimensions to (%u, %u): %d",
-                    width, height, error);
-            return BAD_VALUE;
-        }
-        error = descriptor->setFormat(
-                static_cast<android_pixel_format_t>(format));
-        if (error != GRALLOC1_ERROR_NONE) {
-            ALOGE("Failed to set format to %d: %d", format, error);
-            return BAD_VALUE;
-        }
-        if (mDevice->hasCapability(GRALLOC1_CAPABILITY_LAYERED_BUFFERS)) {
-            error = descriptor->setLayerCount(layerCount);
-            if (error != GRALLOC1_ERROR_NONE) {
-                ALOGE("Failed to set layer count to %u: %d", layerCount, error);
-                return BAD_VALUE;
-            }
-        } else if (layerCount > 1) {
-            ALOGE("Failed to set layer count to %u: capability unsupported",
-                    layerCount);
-            return BAD_VALUE;
-        }
-        error = descriptor->setProducerUsage(
-                static_cast<gralloc1_producer_usage_t>(producerUsage));
-        if (error != GRALLOC1_ERROR_NONE) {
-            ALOGE("Failed to set producer usage to %" PRIx64 ": %d",
-                    producerUsage, error);
-            return BAD_VALUE;
-        }
-        error = descriptor->setConsumerUsage(
-                static_cast<gralloc1_consumer_usage_t>(consumerUsage));
-        if (error != GRALLOC1_ERROR_NONE) {
-            ALOGE("Failed to set consumer usage to %" PRIx64 ": %d",
-                    consumerUsage, error);
-            return BAD_VALUE;
-        }
 
-        error = mDevice->allocate(descriptor, graphicBufferId, handle);
-        if (error != GRALLOC1_ERROR_NONE) {
-            ALOGE("Failed to allocate (%u x %u) layerCount %u format %d "
-                    "producerUsage %" PRIx64 " consumerUsage %" PRIx64 ": %d",
-                    width, height, layerCount, format, producerUsage,
-                    consumerUsage, error);
-            return NO_MEMORY;
-        }
-
-        error = mDevice->getStride(*handle, stride);
-        if (error != GRALLOC1_ERROR_NONE) {
-            ALOGW("Failed to get stride from buffer: %d", error);
-        }
-    }
-
-    if (error == NO_ERROR) {
+    Gralloc2::Error error = mAllocator->allocate(info, stride, handle);
+    if (error == Gralloc2::Error::NONE) {
         Mutex::Autolock _l(sLock);
         KeyedVector<buffer_handle_t, alloc_rec_t>& list(sAllocList);
         uint32_t bpp = bytesPerPixel(format);
@@ -204,25 +134,20 @@
         rec.size = static_cast<size_t>(height * (*stride) * bpp);
         rec.requestorName = std::move(requestorName);
         list.add(*handle, rec);
-    }
 
-    return NO_ERROR;
+        return NO_ERROR;
+    } else {
+        return NO_MEMORY;
+    }
 }
 
 status_t GraphicBufferAllocator::free(buffer_handle_t handle)
 {
     ATRACE_CALL();
 
-    gralloc1_error_t error;
-    if (mAllocator->valid()) {
-        error = static_cast<gralloc1_error_t>(mMapper.freeBuffer(handle));
-    } else {
-        error = mDevice->release(handle);
-    }
-
-    if (error != GRALLOC1_ERROR_NONE) {
-        ALOGE("Failed to free buffer: %d", error);
-    }
+    // We allocated a buffer from the allocator and imported it into the
+    // mapper to get the handle.  We just need to free the handle now.
+    mMapper.freeBuffer(handle);
 
     Mutex::Autolock _l(sLock);
     KeyedVector<buffer_handle_t, alloc_rec_t>& list(sAllocList);
diff --git a/libs/ui/GraphicBufferMapper.cpp b/libs/ui/GraphicBufferMapper.cpp
index 87519bf..b9fa640 100644
--- a/libs/ui/GraphicBufferMapper.cpp
+++ b/libs/ui/GraphicBufferMapper.cpp
@@ -45,10 +45,6 @@
 GraphicBufferMapper::GraphicBufferMapper()
   : mMapper(std::make_unique<const Gralloc2::Mapper>())
 {
-    if (!mMapper->valid()) {
-        mLoader = std::make_unique<Gralloc1::Loader>();
-        mDevice = mLoader->getDevice();
-    }
 }
 
 status_t GraphicBufferMapper::importBuffer(buffer_handle_t rawHandle,
@@ -56,13 +52,8 @@
 {
     ATRACE_CALL();
 
-    Gralloc2::Error error;
-    if (mMapper->valid()) {
-        error = mMapper->importBuffer(hardware::hidl_handle(rawHandle),
-                outHandle);
-    } else {
-        error = Gralloc2::Error::UNSUPPORTED;
-    }
+    Gralloc2::Error error = mMapper->importBuffer(
+            hardware::hidl_handle(rawHandle), outHandle);
 
     ALOGW_IF(error != Gralloc2::Error::NONE, "importBuffer(%p) failed: %d",
             rawHandle, error);
@@ -70,77 +61,13 @@
     return static_cast<status_t>(error);
 }
 
-status_t GraphicBufferMapper::importBuffer(const GraphicBuffer* buffer)
-{
-    ATRACE_CALL();
-
-    ANativeWindowBuffer* nativeBuffer = buffer->getNativeBuffer();
-    buffer_handle_t rawHandle = nativeBuffer->handle;
-
-    gralloc1_error_t error;
-    if (mMapper->valid()) {
-        buffer_handle_t importedHandle;
-        error = static_cast<gralloc1_error_t>(mMapper->importBuffer(
-                    hardware::hidl_handle(rawHandle), &importedHandle));
-        if (error == GRALLOC1_ERROR_NONE) {
-            nativeBuffer->handle = importedHandle;
-        }
-    } else {
-        native_handle_t* clonedHandle = native_handle_clone(rawHandle);
-        if (clonedHandle) {
-            nativeBuffer->handle = clonedHandle;
-            error = mDevice->retain(buffer);
-            if (error != GRALLOC1_ERROR_NONE) {
-                nativeBuffer->handle = rawHandle;
-                native_handle_close(clonedHandle);
-                native_handle_delete(clonedHandle);
-            }
-        } else {
-            error = GRALLOC1_ERROR_NO_RESOURCES;
-        }
-    }
-
-    // the raw handle is owned by GraphicBuffer and is now replaced
-    if (error == GRALLOC1_ERROR_NONE) {
-        native_handle_close(rawHandle);
-        native_handle_delete(const_cast<native_handle_t*>(rawHandle));
-    }
-
-    ALOGW_IF(error != GRALLOC1_ERROR_NONE, "importBuffer(%p) failed: %d",
-            rawHandle, error);
-
-    return error;
-}
-
 status_t GraphicBufferMapper::freeBuffer(buffer_handle_t handle)
 {
     ATRACE_CALL();
 
-    gralloc1_error_t error;
-    if (mMapper->valid()) {
-        mMapper->freeBuffer(handle);
-        error = GRALLOC1_ERROR_NONE;
-    } else {
-        error = mDevice->release(handle);
-        if (!mDevice->hasCapability(GRALLOC1_CAPABILITY_RELEASE_IMPLY_DELETE)) {
-            native_handle_close(handle);
-            native_handle_delete(const_cast<native_handle_t*>(handle));
-        }
-    }
+    mMapper->freeBuffer(handle);
 
-    ALOGW_IF(error != GRALLOC1_ERROR_NONE, "freeBuffer(%p): failed %d",
-            handle, error);
-
-    return error;
-}
-
-static inline gralloc1_rect_t asGralloc1Rect(const Rect& rect) {
-    gralloc1_rect_t outRect{};
-    outRect.left = rect.left;
-    outRect.top = rect.top;
-    outRect.width = rect.width();
-    outRect.height = rect.height();
-    return outRect;
+    return NO_ERROR;
 }
 
 static inline Gralloc2::IMapper::Rect asGralloc2Rect(const Rect& rect) {
@@ -187,26 +114,15 @@
 {
     ATRACE_CALL();
 
-    gralloc1_error_t error;
-    if (mMapper->valid()) {
-        const uint64_t usage =
-            static_cast<uint64_t>(android_convertGralloc1To0Usage(
-                        producerUsage, consumerUsage));
-        error = static_cast<gralloc1_error_t>(mMapper->lock(handle,
-                usage, asGralloc2Rect(bounds), fenceFd, vaddr));
-    } else {
-        gralloc1_rect_t accessRegion = asGralloc1Rect(bounds);
-        sp<Fence> fence = new Fence(fenceFd);
-        error = mDevice->lock(handle,
-                static_cast<gralloc1_producer_usage_t>(producerUsage),
-                static_cast<gralloc1_consumer_usage_t>(consumerUsage),
-                &accessRegion, vaddr, fence);
-    }
+    const uint64_t usage = static_cast<uint64_t>(
+            android_convertGralloc1To0Usage(producerUsage, consumerUsage));
+    Gralloc2::Error error = mMapper->lock(handle, usage,
+            asGralloc2Rect(bounds), fenceFd, vaddr);
 
-    ALOGW_IF(error != GRALLOC1_ERROR_NONE, "lock(%p, ...) failed: %d", handle,
-            error);
+    ALOGW_IF(error != Gralloc2::Error::NONE, "lock(%p, ...) failed: %d",
+            handle, error);
 
-    return error;
+    return static_cast<status_t>(error);
 }
 
 static inline bool isValidYCbCrPlane(const android_flex_plane_t& plane) {
@@ -237,160 +153,28 @@
 {
     ATRACE_CALL();
 
-    gralloc1_rect_t accessRegion = asGralloc1Rect(bounds);
-
-    std::vector<android_flex_plane_t> planes;
-    android_flex_layout_t flexLayout{};
-    gralloc1_error_t error;
-
-    if (mMapper->valid()) {
-        Gralloc2::YCbCrLayout layout;
-        error = static_cast<gralloc1_error_t>(mMapper->lock(handle, usage,
-                asGralloc2Rect(bounds), fenceFd, &layout));
-        if (error == GRALLOC1_ERROR_NONE) {
-            ycbcr->y = layout.y;
-            ycbcr->cb = layout.cb;
-            ycbcr->cr = layout.cr;
-            ycbcr->ystride = static_cast<size_t>(layout.yStride);
-            ycbcr->cstride = static_cast<size_t>(layout.cStride);
-            ycbcr->chroma_step = static_cast<size_t>(layout.chromaStep);
-        }
-
-        return error;
-    } else {
-        sp<Fence> fence = new Fence(fenceFd);
-
-        if (mDevice->hasCapability(GRALLOC1_CAPABILITY_ON_ADAPTER)) {
-            error = mDevice->lockYCbCr(handle,
-                    static_cast<gralloc1_producer_usage_t>(usage),
-                    static_cast<gralloc1_consumer_usage_t>(usage),
-                    &accessRegion, ycbcr, fence);
-            ALOGW_IF(error != GRALLOC1_ERROR_NONE,
-                    "lockYCbCr(%p, ...) failed: %d", handle, error);
-            return error;
-        }
-
-        uint32_t numPlanes = 0;
-        error = mDevice->getNumFlexPlanes(handle, &numPlanes);
-
-        if (error != GRALLOC1_ERROR_NONE) {
-            ALOGV("Failed to retrieve number of flex planes: %d", error);
-            return error;
-        }
-        if (numPlanes < 3) {
-            ALOGV("Not enough planes for YCbCr (%u found)", numPlanes);
-            return GRALLOC1_ERROR_UNSUPPORTED;
-        }
-
-        planes.resize(numPlanes);
-        flexLayout.num_planes = numPlanes;
-        flexLayout.planes = planes.data();
-
-        error = mDevice->lockFlex(handle,
-                static_cast<gralloc1_producer_usage_t>(usage),
-                static_cast<gralloc1_consumer_usage_t>(usage),
-                &accessRegion, &flexLayout, fence);
+    Gralloc2::YCbCrLayout layout;
+    Gralloc2::Error error = mMapper->lock(handle, usage,
+            asGralloc2Rect(bounds), fenceFd, &layout);
+    if (error == Gralloc2::Error::NONE) {
+        ycbcr->y = layout.y;
+        ycbcr->cb = layout.cb;
+        ycbcr->cr = layout.cr;
+        ycbcr->ystride = static_cast<size_t>(layout.yStride);
+        ycbcr->cstride = static_cast<size_t>(layout.cStride);
+        ycbcr->chroma_step = static_cast<size_t>(layout.chromaStep);
     }
 
-    if (error != GRALLOC1_ERROR_NONE) {
-        ALOGW("lockFlex(%p, ...) failed: %d", handle, error);
-        return error;
-    }
-    if (flexLayout.format != FLEX_FORMAT_YCbCr) {
-        ALOGV("Unable to convert flex-format buffer to YCbCr");
-        unlock(handle);
-        return GRALLOC1_ERROR_UNSUPPORTED;
-    }
-
-    // Find planes
-    auto yPlane = planes.cend();
-    auto cbPlane = planes.cend();
-    auto crPlane = planes.cend();
-    for (auto planeIter = planes.cbegin(); planeIter != planes.cend();
-            ++planeIter) {
-        if (planeIter->component == FLEX_COMPONENT_Y) {
-            yPlane = planeIter;
-        } else if (planeIter->component == FLEX_COMPONENT_Cb) {
-            cbPlane = planeIter;
-        } else if (planeIter->component == FLEX_COMPONENT_Cr) {
-            crPlane = planeIter;
-        }
-    }
-    if (yPlane == planes.cend()) {
-        ALOGV("Unable to find Y plane");
-        unlock(handle);
-        return GRALLOC1_ERROR_UNSUPPORTED;
-    }
-    if (cbPlane == planes.cend()) {
-        ALOGV("Unable to find Cb plane");
-        unlock(handle);
-        return GRALLOC1_ERROR_UNSUPPORTED;
-    }
-    if (crPlane == planes.cend()) {
-        ALOGV("Unable to find Cr plane");
-        unlock(handle);
-        return GRALLOC1_ERROR_UNSUPPORTED;
-    }
-
-    // Validate planes
-    if (!isValidYCbCrPlane(*yPlane)) {
-        ALOGV("Y plane is invalid");
-        unlock(handle);
-        return GRALLOC1_ERROR_UNSUPPORTED;
-    }
-    if (!isValidYCbCrPlane(*cbPlane)) {
-        ALOGV("Cb plane is invalid");
-        unlock(handle);
-        return GRALLOC1_ERROR_UNSUPPORTED;
-    }
-    if (!isValidYCbCrPlane(*crPlane)) {
-        ALOGV("Cr plane is invalid");
-        unlock(handle);
-        return GRALLOC1_ERROR_UNSUPPORTED;
-    }
-    if (cbPlane->v_increment != crPlane->v_increment) {
-        ALOGV("Cb and Cr planes have different step (%d vs. %d)",
-                cbPlane->v_increment, crPlane->v_increment);
-        unlock(handle);
-        return GRALLOC1_ERROR_UNSUPPORTED;
-    }
-    if (cbPlane->h_increment != crPlane->h_increment) {
-        ALOGV("Cb and Cr planes have different stride (%d vs. %d)",
-                cbPlane->h_increment, crPlane->h_increment);
-        unlock(handle);
-        return GRALLOC1_ERROR_UNSUPPORTED;
-    }
-
-    // Pack plane data into android_ycbcr struct
-    ycbcr->y = yPlane->top_left;
-    ycbcr->cb = cbPlane->top_left;
-    ycbcr->cr = crPlane->top_left;
-    ycbcr->ystride = static_cast<size_t>(yPlane->v_increment);
-    ycbcr->cstride = static_cast<size_t>(cbPlane->v_increment);
-    ycbcr->chroma_step = static_cast<size_t>(cbPlane->h_increment);
-
-    return error;
+    return static_cast<status_t>(error);
 }
 
 status_t GraphicBufferMapper::unlockAsync(buffer_handle_t handle, int *fenceFd)
 {
     ATRACE_CALL();
 
-    gralloc1_error_t error;
-    if (mMapper->valid()) {
-        *fenceFd = mMapper->unlock(handle);
-        error = GRALLOC1_ERROR_NONE;
-    } else {
-        sp<Fence> fence = Fence::NO_FENCE;
-        error = mDevice->unlock(handle, &fence);
-        if (error != GRALLOC1_ERROR_NONE) {
-            ALOGE("unlock(%p) failed: %d", handle, error);
-            return error;
-        }
+    *fenceFd = mMapper->unlock(handle);
 
-        *fenceFd = fence->dup();
-    }
-    return error;
+    return NO_ERROR;
 }
 
 // ---------------------------------------------------------------------------
diff --git a/libs/vr/libbufferhubqueue/buffer_hub_queue_producer.cpp b/libs/vr/libbufferhubqueue/buffer_hub_queue_producer.cpp
index ebd7da0..e236c31 100644
--- a/libs/vr/libbufferhubqueue/buffer_hub_queue_producer.cpp
+++ b/libs/vr/libbufferhubqueue/buffer_hub_queue_producer.cpp
@@ -450,7 +450,9 @@
 
   std::unique_lock<std::mutex> lock(core_->mutex_);
 
-  if (api != core_->connected_api_) {
+  if (BufferHubQueueCore::kNoConnectedApi == core_->connected_api_) {
+    return NO_INIT;
+  } else if (api != core_->connected_api_) {
     return BAD_VALUE;
   }
 
diff --git a/libs/vr/libdvr/display_manager_client.cpp b/libs/vr/libdvr/display_manager_client.cpp
index 8d84f7b..64c7f16 100644
--- a/libs/vr/libdvr/display_manager_client.cpp
+++ b/libs/vr/libdvr/display_manager_client.cpp
@@ -1,6 +1,7 @@
 #include "include/dvr/display_manager_client.h"
 
 #include <dvr/dvr_buffer.h>
+#include <private/android/AHardwareBufferHelpers.h>
 #include <private/dvr/buffer_hub_client.h>
 #include <private/dvr/display_manager_client_impl.h>
 
@@ -44,10 +45,11 @@
 
 DvrBuffer* dvrDisplayManagerSetupNamedBuffer(DvrDisplayManagerClient* client,
                                              const char* name, size_t size,
-                                             uint64_t producer_usage,
-                                             uint64_t consumer_usage) {
-  // TODO(hendrikw): When we move to gralloc1, pass both producer_usage and
-  // consumer_usage down.
+                                             uint64_t usage0, uint64_t usage1) {
+  uint64_t producer_usage = 0;
+  uint64_t consumer_usage = 0;
+  android::AHardwareBuffer_convertToGrallocUsageBits(
+      &producer_usage, &consumer_usage, usage0, usage1);
   auto ion_buffer = client->client->SetupNamedBuffer(name, size, producer_usage,
                                                      consumer_usage);
   if (ion_buffer) {
diff --git a/libs/vr/libdvr/dvr_api.cpp b/libs/vr/libdvr/dvr_api.cpp
index 5dc4a1b..c4634b1 100644
--- a/libs/vr/libdvr/dvr_api.cpp
+++ b/libs/vr/libdvr/dvr_api.cpp
@@ -53,14 +53,18 @@
     dvr_api->write_buffer_post = dvrWriteBufferPost;
     dvr_api->write_buffer_gain = dvrWriteBufferGain;
     dvr_api->write_buffer_gain_async = dvrWriteBufferGainAsync;
+    dvr_api->write_buffer_get_native_handle = dvrWriteBufferGetNativeHandle;
 
     dvr_api->read_buffer_destroy = dvrReadBufferDestroy;
     dvr_api->read_buffer_get_ahardwarebuffer = dvrReadBufferGetAHardwareBuffer;
     dvr_api->read_buffer_acquire = dvrReadBufferAcquire;
     dvr_api->read_buffer_release = dvrReadBufferRelease;
     dvr_api->read_buffer_release_async = dvrReadBufferReleaseAsync;
+    dvr_api->read_buffer_get_native_handle = dvrReadBufferGetNativeHandle;
+
     dvr_api->buffer_destroy = dvrBufferDestroy;
     dvr_api->buffer_get_ahardwarebuffer = dvrBufferGetAHardwareBuffer;
+    dvr_api->buffer_get_native_handle = dvrBufferGetNativeHandle;
 
     // dvr_buffer_queue.h
     dvr_api->write_buffer_queue_destroy = dvrWriteBufferQueueDestroy;
diff --git a/libs/vr/libdvr/dvr_buffer.cpp b/libs/vr/libdvr/dvr_buffer.cpp
index 0942b3d..28820e7 100644
--- a/libs/vr/libdvr/dvr_buffer.cpp
+++ b/libs/vr/libdvr/dvr_buffer.cpp
@@ -1,5 +1,6 @@
 #include "include/dvr/dvr_buffer.h"
 
+#include <android/hardware_buffer.h>
 #include <private/dvr/buffer_hub_client.h>
 #include <ui/GraphicBuffer.h>
 
@@ -54,6 +55,16 @@
       false /* keep ownership */));
 }
 
+int ConvertToAHardwareBuffer(GraphicBuffer* graphic_buffer,
+                             AHardwareBuffer** hardware_buffer) {
+  if (!hardware_buffer || !graphic_buffer) {
+    return -EINVAL;
+  }
+  *hardware_buffer = reinterpret_cast<AHardwareBuffer*>(graphic_buffer);
+  AHardwareBuffer_acquire(*hardware_buffer);
+  return 0;
+}
+
 }  // anonymous namespace
 
 extern "C" {
@@ -68,9 +79,8 @@
 
 int dvrWriteBufferGetAHardwareBuffer(DvrWriteBuffer* write_buffer,
                                      AHardwareBuffer** hardware_buffer) {
-  *hardware_buffer = reinterpret_cast<AHardwareBuffer*>(
-      write_buffer->write_buffer->buffer()->buffer().get());
-  return 0;
+  return ConvertToAHardwareBuffer(
+      write_buffer->write_buffer->buffer()->buffer().get(), hardware_buffer);
 }
 
 int dvrWriteBufferPost(DvrWriteBuffer* write_buffer, int ready_fence_fd,
@@ -99,9 +109,8 @@
 
 int dvrReadBufferGetAHardwareBuffer(DvrReadBuffer* read_buffer,
                                     AHardwareBuffer** hardware_buffer) {
-  *hardware_buffer = reinterpret_cast<AHardwareBuffer*>(
-      read_buffer->read_buffer->buffer()->buffer().get());
-  return 0;
+  return ConvertToAHardwareBuffer(
+      read_buffer->read_buffer->buffer()->buffer().get(), hardware_buffer);
 }
 
 int dvrReadBufferAcquire(DvrReadBuffer* read_buffer, int* ready_fence_fd,
@@ -127,13 +136,22 @@
 
 int dvrBufferGetAHardwareBuffer(DvrBuffer* buffer,
                                 AHardwareBuffer** hardware_buffer) {
-  if (!hardware_buffer) {
-    return -EINVAL;
-  }
+  return ConvertToAHardwareBuffer(buffer->buffer->buffer().get(),
+                                  hardware_buffer);
+}
 
-  *hardware_buffer =
-      reinterpret_cast<AHardwareBuffer*>(buffer->buffer->buffer().get());
-  return 0;
+const struct native_handle* dvrWriteBufferGetNativeHandle(
+    DvrWriteBuffer* write_buffer) {
+  return write_buffer->write_buffer->native_handle();
+}
+
+const struct native_handle* dvrReadBufferGetNativeHandle(
+    DvrReadBuffer* read_buffer) {
+  return read_buffer->read_buffer->native_handle();
+}
+
+const struct native_handle* dvrBufferGetNativeHandle(DvrBuffer* buffer) {
+  return buffer->buffer->handle();
 }
 
 }  // extern "C"
diff --git a/libs/vr/libdvr/include/dvr/display_manager_client.h b/libs/vr/libdvr/include/dvr/display_manager_client.h
index 4e1f227..8cd948c 100644
--- a/libs/vr/libdvr/include/dvr/display_manager_client.h
+++ b/libs/vr/libdvr/include/dvr/display_manager_client.h
@@ -22,8 +22,7 @@
 
 DvrBuffer* dvrDisplayManagerSetupNamedBuffer(DvrDisplayManagerClient* client,
                                              const char* name, size_t size,
-                                             uint64_t producer_usage,
-                                             uint64_t consumer_usage);
+                                             uint64_t usage0, uint64_t usage1);
 
 // Return an event fd for checking if there was an event on the server
 // Note that the only event which will be flagged is POLLIN. You must use
diff --git a/libs/vr/libdvr/include/dvr/dvr_api.h b/libs/vr/libdvr/include/dvr/dvr_api.h
index a69433d..56f937b 100644
--- a/libs/vr/libdvr/include/dvr/dvr_api.h
+++ b/libs/vr/libdvr/include/dvr/dvr_api.h
@@ -38,6 +38,8 @@
 
 typedef struct DvrSurface DvrSurface;
 
+struct native_handle;
+
 // display_manager_client.h
 typedef int (*DvrDisplayManagerClientGetSurfaceListPtr)(
     DvrDisplayManagerClient* client,
@@ -46,7 +48,7 @@
     DvrDisplayManagerClientSurfaceList* surface_list);
 typedef DvrBuffer* (*DvrDisplayManagerSetupNamedBufferPtr)(
     DvrDisplayManagerClient* client, const char* name, size_t size,
-    uint64_t producer_usage, uint64_t consumer_usage);
+    uint64_t usage0, uint64_t usage1);
 typedef size_t (*DvrDisplayManagerClientSurfaceListGetSizePtr)(
     DvrDisplayManagerClientSurfaceList* surface_list);
 typedef int (*DvrDisplayManagerClientSurfaceListGetSurfaceIdPtr)(
@@ -70,6 +72,8 @@
 typedef int (*DvrWriteBufferGainPtr)(DvrWriteBuffer* client,
                                      int* release_fence_fd);
 typedef int (*DvrWriteBufferGainAsyncPtr)(DvrWriteBuffer* client);
+typedef const struct native_handle* (*DvrWriteBufferGetNativeHandle)(
+    DvrWriteBuffer* write_buffer);
 
 typedef void (*DvrReadBufferDestroyPtr)(DvrReadBuffer* client);
 typedef int (*DvrReadBufferGetAHardwareBufferPtr)(
@@ -80,9 +84,14 @@
 typedef int (*DvrReadBufferReleasePtr)(DvrReadBuffer* client,
                                        int release_fence_fd);
 typedef int (*DvrReadBufferReleaseAsyncPtr)(DvrReadBuffer* client);
+typedef const struct native_handle* (*DvrReadBufferGetNativeHandle)(
+    DvrReadBuffer* read_buffer);
+
 typedef void (*DvrBufferDestroy)(DvrBuffer* buffer);
 typedef int (*DvrBufferGetAHardwareBuffer)(DvrBuffer* buffer,
                                            AHardwareBuffer** hardware_buffer);
+typedef const struct native_handle* (*DvrBufferGetNativeHandle)(
+    DvrBuffer* buffer);
 
 // dvr_buffer_queue.h
 typedef void (*DvrWriteBufferQueueDestroyPtr)(DvrWriteBufferQueue* write_queue);
@@ -238,6 +247,7 @@
   DvrWriteBufferPostPtr write_buffer_post;
   DvrWriteBufferGainPtr write_buffer_gain;
   DvrWriteBufferGainAsyncPtr write_buffer_gain_async;
+  DvrWriteBufferGetNativeHandle write_buffer_get_native_handle;
 
   // Read buffer
   DvrReadBufferDestroyPtr read_buffer_destroy;
@@ -245,8 +255,12 @@
   DvrReadBufferAcquirePtr read_buffer_acquire;
   DvrReadBufferReleasePtr read_buffer_release;
   DvrReadBufferReleaseAsyncPtr read_buffer_release_async;
+  DvrReadBufferGetNativeHandle read_buffer_get_native_handle;
+
+  // Buffer
   DvrBufferDestroy buffer_destroy;
   DvrBufferGetAHardwareBuffer buffer_get_ahardwarebuffer;
+  DvrBufferGetNativeHandle buffer_get_native_handle;
 
   // Write buffer queue
   DvrWriteBufferQueueDestroyPtr write_buffer_queue_destroy;
diff --git a/libs/vr/libdvr/include/dvr/dvr_buffer.h b/libs/vr/libdvr/include/dvr/dvr_buffer.h
index 6c9c4d3..3e8357c 100644
--- a/libs/vr/libdvr/include/dvr/dvr_buffer.h
+++ b/libs/vr/libdvr/include/dvr/dvr_buffer.h
@@ -13,31 +13,40 @@
 typedef struct DvrReadBuffer DvrReadBuffer;
 typedef struct DvrBuffer DvrBuffer;
 typedef struct AHardwareBuffer AHardwareBuffer;
+struct native_handle;
 
 // Write buffer
 void dvrWriteBufferDestroy(DvrWriteBuffer* write_buffer);
 int dvrWriteBufferGetId(DvrWriteBuffer* write_buffer);
+// Caller must call AHardwareBuffer_release on hardware_buffer.
 int dvrWriteBufferGetAHardwareBuffer(DvrWriteBuffer* write_buffer,
                                      AHardwareBuffer** hardware_buffer);
 int dvrWriteBufferPost(DvrWriteBuffer* write_buffer, int ready_fence_fd,
                        const void* meta, size_t meta_size_bytes);
 int dvrWriteBufferGain(DvrWriteBuffer* write_buffer, int* release_fence_fd);
 int dvrWriteBufferGainAsync(DvrWriteBuffer* write_buffer);
+const struct native_handle* dvrWriteBufferGetNativeHandle(
+    DvrWriteBuffer* write_buffer);
 
 // Read buffer
 void dvrReadBufferDestroy(DvrReadBuffer* read_buffer);
 int dvrReadBufferGetId(DvrReadBuffer* read_buffer);
+// Caller must call AHardwareBuffer_release on hardware_buffer.
 int dvrReadBufferGetAHardwareBuffer(DvrReadBuffer* read_buffer,
                                     AHardwareBuffer** hardware_buffer);
 int dvrReadBufferAcquire(DvrReadBuffer* read_buffer, int* ready_fence_fd,
                          void* meta, size_t meta_size_bytes);
 int dvrReadBufferRelease(DvrReadBuffer* read_buffer, int release_fence_fd);
 int dvrReadBufferReleaseAsync(DvrReadBuffer* read_buffer);
+const struct native_handle* dvrReadBufferGetNativeHandle(
+    DvrReadBuffer* read_buffer);
 
 // Buffer
 void dvrBufferDestroy(DvrBuffer* buffer);
+// Caller must call AHardwareBuffer_release on hardware_buffer.
 int dvrBufferGetAHardwareBuffer(DvrBuffer* buffer,
                                 AHardwareBuffer** hardware_buffer);
+const struct native_handle* dvrBufferGetNativeHandle(DvrBuffer* buffer);
 
 #ifdef __cplusplus
 }  // extern "C"
diff --git a/libs/vr/libdvr/tests/dvr_named_buffer-test.cpp b/libs/vr/libdvr/tests/dvr_named_buffer-test.cpp
index cd3285f..2866f47 100644
--- a/libs/vr/libdvr/tests/dvr_named_buffer-test.cpp
+++ b/libs/vr/libdvr/tests/dvr_named_buffer-test.cpp
@@ -42,11 +42,12 @@
   AHardwareBuffer* hardware_buffer1 = nullptr;
   int e1 = dvrBufferGetAHardwareBuffer(buffer1, &hardware_buffer1);
   ASSERT_EQ(0, e1);
+  ASSERT_NE(nullptr, hardware_buffer1);
 
   AHardwareBuffer* hardware_buffer2 = nullptr;
   int e2 = dvrBufferGetAHardwareBuffer(buffer2, &hardware_buffer2);
   ASSERT_EQ(0, e2);
-  ASSERT_NE(nullptr, hardware_buffer1);
+  ASSERT_NE(nullptr, hardware_buffer2);
 
   AHardwareBuffer_Desc desc1 = {};
   AHardwareBuffer_describe(hardware_buffer1, &desc1);
@@ -88,6 +89,10 @@
   ASSERT_EQ(desc3.usage1, 0u);
 
   dvrBufferDestroy(buffer3);
+
+  AHardwareBuffer_release(hardware_buffer1);
+  AHardwareBuffer_release(hardware_buffer2);
+  AHardwareBuffer_release(hardware_buffer3);
 }
 
 TEST_F(DvrNamedBufferTest, TestMultipleNamedBuffers) {
@@ -116,6 +121,35 @@
   dvrBufferDestroy(buffer2);
 }
 
+TEST_F(DvrNamedBufferTest, TestNamedBufferUsage) {
+  const char* buffer_name = "buffer_usage";
+
+  // Set usage0 to AHARDWAREBUFFER_USAGE0_VIDEO_ENCODE. We use this because
+  // internally AHARDWAREBUFFER_USAGE0_VIDEO_ENCODE is converted to
+  // GRALLOC1_CONSUMER_USAGE_VIDEO_ENCODER, and these two values are different.
+  // If all is good, when we get the AHardwareBuffer, it should be converted
+  // back to AHARDWAREBUFFER_USAGE0_VIDEO_ENCODE.
+  const int64_t usage0 = AHARDWAREBUFFER_USAGE0_VIDEO_ENCODE;
+
+  DvrBuffer* setup_buffer =
+      dvrDisplayManagerSetupNamedBuffer(client_, buffer_name, 10, usage0, 0);
+  ASSERT_NE(nullptr, setup_buffer);
+
+  AHardwareBuffer* hardware_buffer = nullptr;
+  int e2 = dvrBufferGetAHardwareBuffer(setup_buffer, &hardware_buffer);
+  ASSERT_EQ(0, e2);
+  ASSERT_NE(nullptr, hardware_buffer);
+
+  AHardwareBuffer_Desc desc = {};
+  AHardwareBuffer_describe(hardware_buffer, &desc);
+
+  ASSERT_EQ(desc.usage0, AHARDWAREBUFFER_USAGE0_VIDEO_ENCODE);
+
+  dvrBufferDestroy(setup_buffer);
+  AHardwareBuffer_release(hardware_buffer);
+}
+
+
 }  // namespace
 
 }  // namespace dvr
diff --git a/libs/vr/libdvrgraphics/gpu_profiler.cpp b/libs/vr/libdvrgraphics/gpu_profiler.cpp
index 49c515f..c8c978d 100644
--- a/libs/vr/libdvrgraphics/gpu_profiler.cpp
+++ b/libs/vr/libdvrgraphics/gpu_profiler.cpp
@@ -7,6 +7,12 @@
 namespace android {
 namespace dvr {
 
+namespace {
+
+constexpr int kMaxPendingQueries = 32;
+
+}  // anonynmous namespace
+
 static int64_t AdjustTimerQueryToNs(int64_t gpu_time) { return gpu_time; }
 
 void GpuProfiler::TimerData::reset() {
@@ -21,6 +27,7 @@
 
 // Enter a scope, records the timestamp for later matching with leave.
 void GpuProfiler::TimerData::enter(int64_t timestamp_ns) {
+  entered = true;
   enter_timestamp_ns = timestamp_ns;
 }
 
@@ -28,6 +35,15 @@
 void GpuProfiler::TimerData::leave(int64_t timestamp_ns, const char* name,
                                    std::weak_ptr<int64_t> duration_ns,
                                    int print_period) {
+  if (!entered) {
+    // We got the leave event but are missing the enter. This can happen if
+    // OnPendingQueryOverflow() is called, or if the calls to enter()/leave()
+    // aren't properly balanced. Ignore the call but print a warning.
+    ALOGW("Ignoring GpuProfiler::TimerData::leave event with no enter event");
+    return;
+  }
+  entered = false;
+
   int64_t elapsed = timestamp_ns - enter_timestamp_ns;
   if (elapsed > 1000 * 1000 * 1000) {
     // More than one second, drop it as invalid data.
@@ -50,12 +66,12 @@
 
 GpuProfiler::GpuProfiler()
     : enable_gpu_tracing_(true),
+      has_gl_context_(false),
       sync_with_cpu_time_(false),
       gl_timer_offset_ns_(0) {
-  SyncGlTimebase();
 }
 
-GpuProfiler::~GpuProfiler() {}
+GpuProfiler::~GpuProfiler() { Clear(); }
 
 bool GpuProfiler::IsGpuProfilingSupported() const {
   // TODO(jbates) check for GL_EXT_disjoint_timer_query
@@ -63,6 +79,9 @@
 }
 
 GLuint GpuProfiler::TryAllocateGlQueryId() {
+  if (pending_gpu_queries_.size() >= kMaxPendingQueries)
+    OnPendingQueryOverflow();
+
   GLuint query_id = 0;
   if (gl_timer_query_id_pool_.empty()) {
     glGenQueries(1, &query_id);
@@ -95,6 +114,35 @@
   }
 }
 
+void GpuProfiler::OnGlContextCreated() {
+  has_gl_context_ = true;
+  gl_timer_offset_ns_ = 0;
+  SyncGlTimebase();
+}
+
+void GpuProfiler::OnGlContextDestroyed() {
+  has_gl_context_ = false;
+  Clear();
+}
+
+void GpuProfiler::Clear() {
+  events_.clear();
+  for (auto& query : pending_gpu_queries_)
+    glDeleteQueries(1, &query.query_id);
+  pending_gpu_queries_.clear();
+  while (!gl_timer_query_id_pool_.empty()) {
+    GLuint id = gl_timer_query_id_pool_.top();
+    gl_timer_query_id_pool_.pop();
+    glDeleteQueries(1, &id);
+  }
+}
+
+void GpuProfiler::OnPendingQueryOverflow() {
+  ALOGW("Reached limit of %d pending queries in GpuProfiler."
+        " Clearing all queries.", kMaxPendingQueries);
+  Clear();
+}
+
 void GpuProfiler::SyncGlTimebase() {
   if (!sync_with_cpu_time_) {
     return;
diff --git a/libs/vr/libdvrgraphics/include/private/dvr/graphics/gpu_profiler.h b/libs/vr/libdvrgraphics/include/private/dvr/graphics/gpu_profiler.h
index 2905d00..c6e752b 100644
--- a/libs/vr/libdvrgraphics/include/private/dvr/graphics/gpu_profiler.h
+++ b/libs/vr/libdvrgraphics/include/private/dvr/graphics/gpu_profiler.h
@@ -38,7 +38,7 @@
   // one of the TRACE_GPU* macros defined below.
   void SetEnableGpuTracing(bool enabled) { enable_gpu_tracing_ = enabled; }
 
-  bool enabled() const { return enable_gpu_tracing_; }
+  bool enabled() const { return enable_gpu_tracing_ && has_gl_context_; }
 
   // Attempt to keep the GPU times in sync with CPU times.
   void SetEnableSyncCpuTime(bool enabled) { sync_with_cpu_time_ = enabled; }
@@ -62,6 +62,14 @@
   void LeaveGlScope(const char* scope_name, std::weak_ptr<int64_t> duration_ns,
                     int print_period);
 
+  // Must be called when the GL context is created. The GpuProfiler will be
+  // inactive until this is called.
+  void OnGlContextCreated();
+
+  // Must be called before the GL context is destroyed. The GpuProfiler will be
+  // inactive until a call to OnGlContextCreated().
+  void OnGlContextDestroyed();
+
  private:
   // Data to queue the pending GPU timer queries that need to be polled
   // for completion.
@@ -105,11 +113,20 @@
     void leave(int64_t timestamp_ns, const char* name,
                std::weak_ptr<int64_t> duration_ns, int print_period);
 
+    bool entered = false;
     int64_t total_elapsed_ns = 0;
     int64_t enter_timestamp_ns = 0;
     int num_events = 0;
   };
 
+  // Clear out events and free GL resources.
+  void Clear();
+
+  // Called when we detect that we've overflowed the pending query queue. This
+  // shouldn't occur in practice, and probably indicates some internal
+  // mismanagement of the gl query objects.
+  void OnPendingQueryOverflow();
+
   // Synchronises the GL timebase with the CallTraceManager timebase.
   void SyncGlTimebase();
 
@@ -119,6 +136,10 @@
   // Setting for enabling GPU tracing.
   bool enable_gpu_tracing_;
 
+  // True if we have a GL context, false otherwise. When the GpuProfiler is
+  // first created we assume no GL context.
+  bool has_gl_context_;
+
   // Setting for synchronizing GPU timestamps with CPU time.
   bool sync_with_cpu_time_;
 
diff --git a/libs/vr/libpdx_default_transport/pdx_benchmarks.cpp b/libs/vr/libpdx_default_transport/pdx_benchmarks.cpp
index 0b658fb..fa0adf0 100644
--- a/libs/vr/libpdx_default_transport/pdx_benchmarks.cpp
+++ b/libs/vr/libpdx_default_transport/pdx_benchmarks.cpp
@@ -516,9 +516,8 @@
     std::cerr << "Starting service instance " << service_id_counter
               << std::endl;
     auto service = BenchmarkService::Create(
-        android::pdx::default_transport::Endpoint::Create(
+        android::pdx::default_transport::Endpoint::CreateAndBindSocket(
             GetServicePath(path, service_id_counter),
-            android::pdx::default_transport::Endpoint::kDefaultMode,
             android::pdx::default_transport::Endpoint::kBlocking));
     if (!service) {
       std::cerr << "Failed to create service instance!!" << std::endl;
diff --git a/libs/vr/libpdx_uds/Android.bp b/libs/vr/libpdx_uds/Android.bp
index a73ba34..f2bcc0c 100644
--- a/libs/vr/libpdx_uds/Android.bp
+++ b/libs/vr/libpdx_uds/Android.bp
@@ -35,10 +35,12 @@
         "-Werror",
     ],
     srcs: [
+        "ipc_helper_tests.cpp",
         "remote_method_tests.cpp",
         "service_framework_tests.cpp",
     ],
     static_libs: [
+        "libgmock",
         "libpdx_uds",
         "libpdx",
     ],
diff --git a/libs/vr/libpdx_uds/ipc_helper.cpp b/libs/vr/libpdx_uds/ipc_helper.cpp
index d604f62..b675894 100644
--- a/libs/vr/libpdx_uds/ipc_helper.cpp
+++ b/libs/vr/libpdx_uds/ipc_helper.cpp
@@ -18,6 +18,150 @@
 namespace pdx {
 namespace uds {
 
+namespace {
+
+// Default implementations of Send/Receive interfaces to use standard socket
+// send/sendmsg/recv/recvmsg functions.
+class SocketSender : public SendInterface {
+ public:
+  ssize_t Send(int socket_fd, const void* data, size_t size,
+               int flags) override {
+    return send(socket_fd, data, size, flags);
+  }
+  ssize_t SendMessage(int socket_fd, const msghdr* msg, int flags) override {
+    return sendmsg(socket_fd, msg, flags);
+  }
+} g_socket_sender;
+
+class SocketReceiver : public RecvInterface {
+ public:
+  ssize_t Receive(int socket_fd, void* data, size_t size, int flags) override {
+    return recv(socket_fd, data, size, flags);
+  }
+  ssize_t ReceiveMessage(int socket_fd, msghdr* msg, int flags) override {
+    return recvmsg(socket_fd, msg, flags);
+  }
+} g_socket_receiver;
+
+}  // anonymous namespace
+
+// Helper wrappers around send()/sendmsg() which repeat send() calls on data
+// that was not sent with the initial call to send/sendmsg. This is important to
+// handle transmissions interrupted by signals.
+Status<void> SendAll(SendInterface* sender, const BorrowedHandle& socket_fd,
+                     const void* data, size_t size) {
+  Status<void> ret;
+  const uint8_t* ptr = static_cast<const uint8_t*>(data);
+  while (size > 0) {
+    ssize_t size_written =
+        RETRY_EINTR(sender->Send(socket_fd.Get(), ptr, size, MSG_NOSIGNAL));
+    if (size_written < 0) {
+      ret.SetError(errno);
+      ALOGE("SendAll: Failed to send data over socket: %s",
+            ret.GetErrorMessage().c_str());
+      break;
+    }
+    size -= size_written;
+    ptr += size_written;
+  }
+  return ret;
+}
+
+Status<void> SendMsgAll(SendInterface* sender, const BorrowedHandle& socket_fd,
+                        const msghdr* msg) {
+  Status<void> ret;
+  ssize_t sent_size =
+      RETRY_EINTR(sender->SendMessage(socket_fd.Get(), msg, MSG_NOSIGNAL));
+  if (sent_size < 0) {
+    ret.SetError(errno);
+    ALOGE("SendMsgAll: Failed to send data over socket: %s",
+          ret.GetErrorMessage().c_str());
+    return ret;
+  }
+
+  ssize_t chunk_start_offset = 0;
+  for (size_t i = 0; i < msg->msg_iovlen; i++) {
+    ssize_t chunk_end_offset = chunk_start_offset + msg->msg_iov[i].iov_len;
+    if (sent_size < chunk_end_offset) {
+      size_t offset_within_chunk = sent_size - chunk_start_offset;
+      size_t data_size = msg->msg_iov[i].iov_len - offset_within_chunk;
+      const uint8_t* chunk_base =
+          static_cast<const uint8_t*>(msg->msg_iov[i].iov_base);
+      ret = SendAll(sender, socket_fd, chunk_base + offset_within_chunk,
+                    data_size);
+      if (!ret)
+        break;
+      sent_size += data_size;
+    }
+    chunk_start_offset = chunk_end_offset;
+  }
+  return ret;
+}
+
+// Helper wrappers around recv()/recvmsg() which repeat recv() calls on data
+// that was not received with the initial call to recvmsg(). This is important
+// to handle transmissions interrupted by signals as well as the case when
+// initial data did not arrive in a single chunk over the socket (e.g. socket
+// buffer was full at the time of transmission, and only portion of initial
+// message was sent and the rest was blocked until the buffer was cleared by the
+// receiving side).
+Status<void> RecvMsgAll(RecvInterface* receiver,
+                        const BorrowedHandle& socket_fd, msghdr* msg) {
+  Status<void> ret;
+  ssize_t size_read = RETRY_EINTR(receiver->ReceiveMessage(
+      socket_fd.Get(), msg, MSG_WAITALL | MSG_CMSG_CLOEXEC));
+  if (size_read < 0) {
+    ret.SetError(errno);
+    ALOGE("RecvMsgAll: Failed to receive data from socket: %s",
+          ret.GetErrorMessage().c_str());
+    return ret;
+  } else if (size_read == 0) {
+    ret.SetError(ESHUTDOWN);
+    ALOGW("RecvMsgAll: Socket has been shut down");
+    return ret;
+  }
+
+  ssize_t chunk_start_offset = 0;
+  for (size_t i = 0; i < msg->msg_iovlen; i++) {
+    ssize_t chunk_end_offset = chunk_start_offset + msg->msg_iov[i].iov_len;
+    if (size_read < chunk_end_offset) {
+      size_t offset_within_chunk = size_read - chunk_start_offset;
+      size_t data_size = msg->msg_iov[i].iov_len - offset_within_chunk;
+      uint8_t* chunk_base = static_cast<uint8_t*>(msg->msg_iov[i].iov_base);
+      ret = RecvAll(receiver, socket_fd, chunk_base + offset_within_chunk,
+                    data_size);
+      if (!ret)
+        break;
+      size_read += data_size;
+    }
+    chunk_start_offset = chunk_end_offset;
+  }
+  return ret;
+}
+
+Status<void> RecvAll(RecvInterface* receiver, const BorrowedHandle& socket_fd,
+                     void* data, size_t size) {
+  Status<void> ret;
+  uint8_t* ptr = static_cast<uint8_t*>(data);
+  while (size > 0) {
+    ssize_t size_read = RETRY_EINTR(receiver->Receive(
+        socket_fd.Get(), ptr, size, MSG_WAITALL | MSG_CMSG_CLOEXEC));
+    if (size_read < 0) {
+      ret.SetError(errno);
+      ALOGE("RecvAll: Failed to receive data from socket: %s",
+            ret.GetErrorMessage().c_str());
+      break;
+    } else if (size_read == 0) {
+      ret.SetError(ESHUTDOWN);
+      ALOGW("RecvAll: Socket has been shut down");
+      break;
+    }
+    size -= size_read;
+    ptr += size_read;
+  }
+  return ret;
+}
+
 uint32_t kMagicPreamble = 0x7564736d;  // 'udsm'.
 
 struct MessagePreamble {
@@ -32,17 +176,14 @@
 
 Status<void> SendPayload::Send(const BorrowedHandle& socket_fd,
                                const ucred* cred) {
+  SendInterface* sender = sender_ ? sender_ : &g_socket_sender;
   MessagePreamble preamble;
   preamble.magic = kMagicPreamble;
   preamble.data_size = buffer_.size();
   preamble.fd_count = file_handles_.size();
-
-  ssize_t ret = RETRY_EINTR(
-      send(socket_fd.Get(), &preamble, sizeof(preamble), MSG_NOSIGNAL));
-  if (ret < 0)
-    return ErrorStatus(errno);
-  if (ret != sizeof(preamble))
-    return ErrorStatus(EIO);
+  Status<void> ret = SendAll(sender, socket_fd, &preamble, sizeof(preamble));
+  if (!ret)
+    return ret;
 
   msghdr msg = {};
   iovec recv_vect = {buffer_.data(), buffer_.size()};
@@ -72,12 +213,7 @@
     }
   }
 
-  ret = RETRY_EINTR(sendmsg(socket_fd.Get(), &msg, MSG_NOSIGNAL));
-  if (ret < 0)
-    return ErrorStatus(errno);
-  if (static_cast<size_t>(ret) != buffer_.size())
-    return ErrorStatus(EIO);
-  return {};
+  return SendMsgAll(sender, socket_fd, &msg);
 }
 
 // MessageWriter
@@ -132,15 +268,16 @@
 
 Status<void> ReceivePayload::Receive(const BorrowedHandle& socket_fd,
                                      ucred* cred) {
+  RecvInterface* receiver = receiver_ ? receiver_ : &g_socket_receiver;
   MessagePreamble preamble;
-  ssize_t ret = RETRY_EINTR(
-      recv(socket_fd.Get(), &preamble, sizeof(preamble), MSG_WAITALL));
-  if (ret < 0)
-    return ErrorStatus(errno);
-  else if (ret == 0)
-    return ErrorStatus(ESHUTDOWN);
-  else if (ret != sizeof(preamble) || preamble.magic != kMagicPreamble)
-    return ErrorStatus(EIO);
+  Status<void> ret = RecvAll(receiver, socket_fd, &preamble, sizeof(preamble));
+  if (!ret)
+    return ret;
+
+  if (preamble.magic != kMagicPreamble) {
+    ret.SetError(EIO);
+    return ret;
+  }
 
   buffer_.resize(preamble.data_size);
   file_handles_.clear();
@@ -159,13 +296,9 @@
     msg.msg_control = alloca(msg.msg_controllen);
   }
 
-  ret = RETRY_EINTR(recvmsg(socket_fd.Get(), &msg, MSG_WAITALL));
-  if (ret < 0)
-    return ErrorStatus(errno);
-  else if (ret == 0)
-    return ErrorStatus(ESHUTDOWN);
-  else if (static_cast<uint32_t>(ret) != preamble.data_size)
-    return ErrorStatus(EIO);
+  ret = RecvMsgAll(receiver, socket_fd, &msg);
+  if (!ret)
+    return ret;
 
   bool cred_available = false;
   file_handles_.reserve(preamble.fd_count);
@@ -186,11 +319,10 @@
     cmsg = CMSG_NXTHDR(&msg, cmsg);
   }
 
-  if (cred && !cred_available) {
-    return ErrorStatus(EIO);
-  }
+  if (cred && !cred_available)
+    ret.SetError(EIO);
 
-  return {};
+  return ret;
 }
 
 // MessageReader
@@ -223,13 +355,7 @@
 
 Status<void> SendData(const BorrowedHandle& socket_fd, const void* data,
                       size_t size) {
-  ssize_t size_written =
-      RETRY_EINTR(send(socket_fd.Get(), data, size, MSG_NOSIGNAL));
-  if (size_written < 0)
-    return ErrorStatus(errno);
-  if (static_cast<size_t>(size_written) != size)
-    return ErrorStatus(EIO);
-  return {};
+  return SendAll(&g_socket_sender, socket_fd, data, size);
 }
 
 Status<void> SendDataVector(const BorrowedHandle& socket_fd, const iovec* data,
@@ -237,26 +363,12 @@
   msghdr msg = {};
   msg.msg_iov = const_cast<iovec*>(data);
   msg.msg_iovlen = count;
-  ssize_t size_written =
-      RETRY_EINTR(sendmsg(socket_fd.Get(), &msg, MSG_NOSIGNAL));
-  if (size_written < 0)
-    return ErrorStatus(errno);
-  if (static_cast<size_t>(size_written) != CountVectorSize(data, count))
-    return ErrorStatus(EIO);
-  return {};
+  return SendMsgAll(&g_socket_sender, socket_fd, &msg);
 }
 
 Status<void> ReceiveData(const BorrowedHandle& socket_fd, void* data,
                          size_t size) {
-  ssize_t size_read =
-      RETRY_EINTR(recv(socket_fd.Get(), data, size, MSG_WAITALL));
-  if (size_read < 0)
-    return ErrorStatus(errno);
-  else if (size_read == 0)
-    return ErrorStatus(ESHUTDOWN);
-  else if (static_cast<size_t>(size_read) != size)
-    return ErrorStatus(EIO);
-  return {};
+  return RecvAll(&g_socket_receiver, socket_fd, data, size);
 }
 
 Status<void> ReceiveDataVector(const BorrowedHandle& socket_fd,
@@ -264,14 +376,7 @@
   msghdr msg = {};
   msg.msg_iov = const_cast<iovec*>(data);
   msg.msg_iovlen = count;
-  ssize_t size_read = RETRY_EINTR(recvmsg(socket_fd.Get(), &msg, MSG_WAITALL));
-  if (size_read < 0)
-    return ErrorStatus(errno);
-  else if (size_read == 0)
-    return ErrorStatus(ESHUTDOWN);
-  else if (static_cast<size_t>(size_read) != CountVectorSize(data, count))
-    return ErrorStatus(EIO);
-  return {};
+  return RecvMsgAll(&g_socket_receiver, socket_fd, &msg);
 }
 
 size_t CountVectorSize(const iovec* vector, size_t count) {
diff --git a/libs/vr/libpdx_uds/ipc_helper_tests.cpp b/libs/vr/libpdx_uds/ipc_helper_tests.cpp
new file mode 100644
index 0000000..bfa827e
--- /dev/null
+++ b/libs/vr/libpdx_uds/ipc_helper_tests.cpp
@@ -0,0 +1,365 @@
+#include "uds/ipc_helper.h"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+using testing::Return;
+using testing::SetErrnoAndReturn;
+using testing::_;
+
+using android::pdx::BorrowedHandle;
+using android::pdx::uds::SendInterface;
+using android::pdx::uds::RecvInterface;
+using android::pdx::uds::SendAll;
+using android::pdx::uds::SendMsgAll;
+using android::pdx::uds::RecvAll;
+using android::pdx::uds::RecvMsgAll;
+
+namespace {
+
+// Useful constants for tests.
+static constexpr intptr_t kPtr = 1234;
+static constexpr int kSocketFd = 5678;
+static const BorrowedHandle kSocket{kSocketFd};
+
+// Helper functions to construct test data pointer values.
+void* IntToPtr(intptr_t value) { return reinterpret_cast<void*>(value); }
+const void* IntToConstPtr(intptr_t value) {
+  return reinterpret_cast<const void*>(value);
+}
+
+// Mock classes for SendInterface/RecvInterface.
+class MockSender : public SendInterface {
+ public:
+  MOCK_METHOD4(Send, ssize_t(int socket_fd, const void* data, size_t size,
+                             int flags));
+  MOCK_METHOD3(SendMessage,
+               ssize_t(int socket_fd, const msghdr* msg, int flags));
+};
+
+class MockReceiver : public RecvInterface {
+ public:
+  MOCK_METHOD4(Receive,
+               ssize_t(int socket_fd, void* data, size_t size, int flags));
+  MOCK_METHOD3(ReceiveMessage, ssize_t(int socket_fd, msghdr* msg, int flags));
+};
+
+// Test case classes.
+class SendTest : public testing::Test {
+ public:
+  SendTest() {
+    ON_CALL(sender_, Send(_, _, _, _))
+        .WillByDefault(SetErrnoAndReturn(EIO, -1));
+    ON_CALL(sender_, SendMessage(_, _, _))
+        .WillByDefault(SetErrnoAndReturn(EIO, -1));
+  }
+
+ protected:
+  MockSender sender_;
+};
+
+class RecvTest : public testing::Test {
+ public:
+  RecvTest() {
+    ON_CALL(receiver_, Receive(_, _, _, _))
+        .WillByDefault(SetErrnoAndReturn(EIO, -1));
+    ON_CALL(receiver_, ReceiveMessage(_, _, _))
+        .WillByDefault(SetErrnoAndReturn(EIO, -1));
+  }
+
+ protected:
+  MockReceiver receiver_;
+};
+
+class MessageTestBase : public testing::Test {
+ public:
+  MessageTestBase() {
+    memset(&msg_, 0, sizeof(msg_));
+    msg_.msg_iovlen = data_.size();
+    msg_.msg_iov = data_.data();
+  }
+
+ protected:
+  static constexpr intptr_t kPtr1 = kPtr;
+  static constexpr intptr_t kPtr2 = kPtr + 200;
+  static constexpr intptr_t kPtr3 = kPtr + 1000;
+
+  MockSender sender_;
+  msghdr msg_;
+  std::vector<iovec> data_{
+      {IntToPtr(kPtr1), 100}, {IntToPtr(kPtr2), 200}, {IntToPtr(kPtr3), 300}};
+};
+
+class SendMessageTest : public MessageTestBase {
+ public:
+  SendMessageTest() {
+    ON_CALL(sender_, Send(_, _, _, _))
+        .WillByDefault(SetErrnoAndReturn(EIO, -1));
+    ON_CALL(sender_, SendMessage(_, _, _))
+        .WillByDefault(SetErrnoAndReturn(EIO, -1));
+  }
+
+ protected:
+  MockSender sender_;
+};
+
+class RecvMessageTest : public MessageTestBase {
+ public:
+  RecvMessageTest() {
+    ON_CALL(receiver_, Receive(_, _, _, _))
+        .WillByDefault(SetErrnoAndReturn(EIO, -1));
+    ON_CALL(receiver_, ReceiveMessage(_, _, _))
+        .WillByDefault(SetErrnoAndReturn(EIO, -1));
+  }
+
+ protected:
+  MockReceiver receiver_;
+};
+
+// Actual tests.
+
+// SendAll
+TEST_F(SendTest, Complete) {
+  EXPECT_CALL(sender_, Send(kSocketFd, IntToConstPtr(kPtr), 100, MSG_NOSIGNAL))
+      .WillOnce(Return(100));
+
+  auto status = SendAll(&sender_, kSocket, IntToConstPtr(kPtr), 100);
+  EXPECT_TRUE(status);
+}
+
+TEST_F(SendTest, Signal) {
+  EXPECT_CALL(sender_, Send(kSocketFd, IntToConstPtr(kPtr), 100, MSG_NOSIGNAL))
+      .WillOnce(Return(20));
+  EXPECT_CALL(sender_,
+              Send(kSocketFd, IntToConstPtr(kPtr + 20), 80, MSG_NOSIGNAL))
+      .WillOnce(Return(40));
+  EXPECT_CALL(sender_,
+              Send(kSocketFd, IntToConstPtr(kPtr + 60), 40, MSG_NOSIGNAL))
+      .WillOnce(Return(40));
+
+  auto status = SendAll(&sender_, kSocket, IntToConstPtr(kPtr), 100);
+  EXPECT_TRUE(status);
+}
+
+TEST_F(SendTest, Eintr) {
+  EXPECT_CALL(sender_, Send(kSocketFd, IntToConstPtr(kPtr), 100, MSG_NOSIGNAL))
+      .WillOnce(SetErrnoAndReturn(EINTR, -1))
+      .WillOnce(Return(100));
+
+  auto status = SendAll(&sender_, kSocket, IntToConstPtr(kPtr), 100);
+  EXPECT_TRUE(status);
+}
+
+TEST_F(SendTest, Error) {
+  EXPECT_CALL(sender_, Send(kSocketFd, IntToConstPtr(kPtr), 100, MSG_NOSIGNAL))
+      .WillOnce(SetErrnoAndReturn(EIO, -1));
+
+  auto status = SendAll(&sender_, kSocket, IntToConstPtr(kPtr), 100);
+  ASSERT_FALSE(status);
+  EXPECT_EQ(EIO, status.error());
+}
+
+TEST_F(SendTest, Error2) {
+  EXPECT_CALL(sender_, Send(kSocketFd, IntToConstPtr(kPtr), 100, MSG_NOSIGNAL))
+      .WillOnce(Return(50));
+  EXPECT_CALL(sender_,
+              Send(kSocketFd, IntToConstPtr(kPtr + 50), 50, MSG_NOSIGNAL))
+      .WillOnce(SetErrnoAndReturn(EIO, -1));
+
+  auto status = SendAll(&sender_, kSocket, IntToConstPtr(kPtr), 100);
+  ASSERT_FALSE(status);
+  EXPECT_EQ(EIO, status.error());
+}
+
+// RecvAll
+TEST_F(RecvTest, Complete) {
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr), 100,
+                                 MSG_WAITALL | MSG_CMSG_CLOEXEC))
+      .WillOnce(Return(100));
+
+  auto status = RecvAll(&receiver_, kSocket, IntToPtr(kPtr), 100);
+  EXPECT_TRUE(status);
+}
+
+TEST_F(RecvTest, Signal) {
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr), 100, _))
+      .WillOnce(Return(20));
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr + 20), 80, _))
+      .WillOnce(Return(40));
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr + 60), 40, _))
+      .WillOnce(Return(40));
+
+  auto status = RecvAll(&receiver_, kSocket, IntToPtr(kPtr), 100);
+  EXPECT_TRUE(status);
+}
+
+TEST_F(RecvTest, Eintr) {
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr), 100, _))
+      .WillOnce(SetErrnoAndReturn(EINTR, -1))
+      .WillOnce(Return(100));
+
+  auto status = RecvAll(&receiver_, kSocket, IntToPtr(kPtr), 100);
+  EXPECT_TRUE(status);
+}
+
+TEST_F(RecvTest, Error) {
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr), 100, _))
+      .WillOnce(SetErrnoAndReturn(EIO, -1));
+
+  auto status = RecvAll(&receiver_, kSocket, IntToPtr(kPtr), 100);
+  ASSERT_FALSE(status);
+  EXPECT_EQ(EIO, status.error());
+}
+
+TEST_F(RecvTest, Error2) {
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr), 100, _))
+      .WillOnce(Return(30));
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr + 30), 70, _))
+      .WillOnce(SetErrnoAndReturn(EIO, -1));
+
+  auto status = RecvAll(&receiver_, kSocket, IntToPtr(kPtr), 100);
+  ASSERT_FALSE(status);
+  EXPECT_EQ(EIO, status.error());
+}
+
+// SendMsgAll
+TEST_F(SendMessageTest, Complete) {
+  EXPECT_CALL(sender_, SendMessage(kSocketFd, &msg_, MSG_NOSIGNAL))
+      .WillOnce(Return(600));
+
+  auto status = SendMsgAll(&sender_, kSocket, &msg_);
+  EXPECT_TRUE(status);
+}
+
+TEST_F(SendMessageTest, Partial) {
+  EXPECT_CALL(sender_, SendMessage(kSocketFd, &msg_, _)).WillOnce(Return(70));
+  EXPECT_CALL(sender_, Send(kSocketFd, IntToConstPtr(kPtr1 + 70), 30, _))
+      .WillOnce(Return(30));
+  EXPECT_CALL(sender_, Send(kSocketFd, IntToConstPtr(kPtr2), 200, _))
+      .WillOnce(Return(190));
+  EXPECT_CALL(sender_, Send(kSocketFd, IntToConstPtr(kPtr2 + 190), 10, _))
+      .WillOnce(Return(10));
+  EXPECT_CALL(sender_, Send(kSocketFd, IntToConstPtr(kPtr3), 300, _))
+      .WillOnce(Return(300));
+
+  auto status = SendMsgAll(&sender_, kSocket, &msg_);
+  EXPECT_TRUE(status);
+}
+
+TEST_F(SendMessageTest, Partial2) {
+  EXPECT_CALL(sender_, SendMessage(kSocketFd, &msg_, _)).WillOnce(Return(310));
+  EXPECT_CALL(sender_, Send(kSocketFd, IntToConstPtr(kPtr3 + 10), 290, _))
+      .WillOnce(Return(290));
+
+  auto status = SendMsgAll(&sender_, kSocket, &msg_);
+  EXPECT_TRUE(status);
+}
+
+TEST_F(SendMessageTest, Eintr) {
+  EXPECT_CALL(sender_, SendMessage(kSocketFd, &msg_, _))
+      .WillOnce(SetErrnoAndReturn(EINTR, -1))
+      .WillOnce(Return(70));
+  EXPECT_CALL(sender_, Send(kSocketFd, IntToConstPtr(kPtr1 + 70), 30, _))
+      .WillOnce(SetErrnoAndReturn(EINTR, -1))
+      .WillOnce(Return(30));
+  EXPECT_CALL(sender_, Send(kSocketFd, IntToConstPtr(kPtr2), 200, _))
+      .WillOnce(Return(200));
+  EXPECT_CALL(sender_, Send(kSocketFd, IntToConstPtr(kPtr3), 300, _))
+      .WillOnce(Return(300));
+
+  auto status = SendMsgAll(&sender_, kSocket, &msg_);
+  EXPECT_TRUE(status);
+}
+
+TEST_F(SendMessageTest, Error) {
+  EXPECT_CALL(sender_, SendMessage(kSocketFd, &msg_, _))
+      .WillOnce(SetErrnoAndReturn(EBADF, -1));
+
+  auto status = SendMsgAll(&sender_, kSocket, &msg_);
+  ASSERT_FALSE(status);
+  EXPECT_EQ(EBADF, status.error());
+}
+
+TEST_F(SendMessageTest, Error2) {
+  EXPECT_CALL(sender_, SendMessage(kSocketFd, &msg_, _)).WillOnce(Return(20));
+  EXPECT_CALL(sender_, Send(kSocketFd, IntToConstPtr(kPtr1 + 20), 80, _))
+      .WillOnce(SetErrnoAndReturn(EBADF, -1));
+
+  auto status = SendMsgAll(&sender_, kSocket, &msg_);
+  ASSERT_FALSE(status);
+  EXPECT_EQ(EBADF, status.error());
+}
+
+// RecvMsgAll
+TEST_F(RecvMessageTest, Complete) {
+  EXPECT_CALL(receiver_,
+              ReceiveMessage(kSocketFd, &msg_, MSG_WAITALL | MSG_CMSG_CLOEXEC))
+      .WillOnce(Return(600));
+
+  auto status = RecvMsgAll(&receiver_, kSocket, &msg_);
+  EXPECT_TRUE(status);
+}
+
+TEST_F(RecvMessageTest, Partial) {
+  EXPECT_CALL(receiver_, ReceiveMessage(kSocketFd, &msg_, _))
+      .WillOnce(Return(70));
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr1 + 70), 30, _))
+      .WillOnce(Return(30));
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr2), 200, _))
+      .WillOnce(Return(190));
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr2 + 190), 10, _))
+      .WillOnce(Return(10));
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr3), 300, _))
+      .WillOnce(Return(300));
+
+  auto status = RecvMsgAll(&receiver_, kSocket, &msg_);
+  EXPECT_TRUE(status);
+}
+
+TEST_F(RecvMessageTest, Partial2) {
+  EXPECT_CALL(receiver_, ReceiveMessage(kSocketFd, &msg_, _))
+      .WillOnce(Return(310));
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr3 + 10), 290, _))
+      .WillOnce(Return(290));
+
+  auto status = RecvMsgAll(&receiver_, kSocket, &msg_);
+  EXPECT_TRUE(status);
+}
+
+TEST_F(RecvMessageTest, Eintr) {
+  EXPECT_CALL(receiver_, ReceiveMessage(kSocketFd, &msg_, _))
+      .WillOnce(SetErrnoAndReturn(EINTR, -1))
+      .WillOnce(Return(70));
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr1 + 70), 30, _))
+      .WillOnce(SetErrnoAndReturn(EINTR, -1))
+      .WillOnce(Return(30));
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr2), 200, _))
+      .WillOnce(Return(200));
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr3), 300, _))
+      .WillOnce(Return(300));
+
+  auto status = RecvMsgAll(&receiver_, kSocket, &msg_);
+  EXPECT_TRUE(status);
+}
+
+TEST_F(RecvMessageTest, Error) {
+  EXPECT_CALL(receiver_, ReceiveMessage(kSocketFd, &msg_, _))
+      .WillOnce(SetErrnoAndReturn(EBADF, -1));
+
+  auto status = RecvMsgAll(&receiver_, kSocket, &msg_);
+  ASSERT_FALSE(status);
+  EXPECT_EQ(EBADF, status.error());
+}
+
+TEST_F(RecvMessageTest, Error2) {
+  EXPECT_CALL(receiver_, ReceiveMessage(kSocketFd, &msg_, _))
+      .WillOnce(Return(20));
+  EXPECT_CALL(receiver_, Receive(kSocketFd, IntToPtr(kPtr1 + 20), 80, _))
+      .WillOnce(SetErrnoAndReturn(EBADF, -1));
+
+  auto status = RecvMsgAll(&receiver_, kSocket, &msg_);
+  ASSERT_FALSE(status);
+  EXPECT_EQ(EBADF, status.error());
+}
+
+}  // namespace
diff --git a/libs/vr/libpdx_uds/private/uds/ipc_helper.h b/libs/vr/libpdx_uds/private/uds/ipc_helper.h
index 82950a2..5b7e5ff 100644
--- a/libs/vr/libpdx_uds/private/uds/ipc_helper.h
+++ b/libs/vr/libpdx_uds/private/uds/ipc_helper.h
@@ -14,6 +14,38 @@
 namespace pdx {
 namespace uds {
 
+// Test interfaces used for unit-testing payload sending/receiving over sockets.
+class SendInterface {
+ public:
+  virtual ssize_t Send(int socket_fd, const void* data, size_t size,
+                       int flags) = 0;
+  virtual ssize_t SendMessage(int socket_fd, const msghdr* msg, int flags) = 0;
+
+ protected:
+  virtual ~SendInterface() = default;
+};
+
+class RecvInterface {
+ public:
+  virtual ssize_t Receive(int socket_fd, void* data, size_t size,
+                          int flags) = 0;
+  virtual ssize_t ReceiveMessage(int socket_fd, msghdr* msg, int flags) = 0;
+
+ protected:
+  virtual ~RecvInterface() = default;
+};
+
+// Helper methods that allow to send/receive data through abstract interfaces.
+// Useful for mocking out the underlying socket I/O.
+Status<void> SendAll(SendInterface* sender, const BorrowedHandle& socket_fd,
+                     const void* data, size_t size);
+Status<void> SendMsgAll(SendInterface* sender, const BorrowedHandle& socket_fd,
+                        const msghdr* msg);
+Status<void> RecvAll(RecvInterface* receiver, const BorrowedHandle& socket_fd,
+                     void* data, size_t size);
+Status<void> RecvMsgAll(RecvInterface* receiver,
+                        const BorrowedHandle& socket_fd, msghdr* msg);
+
 #define RETRY_EINTR(fnc_call)                 \
   ([&]() -> decltype(fnc_call) {              \
     decltype(fnc_call) result;                \
@@ -25,6 +57,7 @@
 
 class SendPayload : public MessageWriter, public OutputResourceMapper {
  public:
+  SendPayload(SendInterface* sender = nullptr) : sender_{sender} {}
   Status<void> Send(const BorrowedHandle& socket_fd);
   Status<void> Send(const BorrowedHandle& socket_fd, const ucred* cred);
 
@@ -44,12 +77,14 @@
       const RemoteChannelHandle& handle) override;
 
  private:
+  SendInterface* sender_;
   ByteBuffer buffer_;
   std::vector<int> file_handles_;
 };
 
 class ReceivePayload : public MessageReader, public InputResourceMapper {
  public:
+  ReceivePayload(RecvInterface* receiver = nullptr) : receiver_{receiver} {}
   Status<void> Receive(const BorrowedHandle& socket_fd);
   Status<void> Receive(const BorrowedHandle& socket_fd, ucred* cred);
 
@@ -64,6 +99,7 @@
                         LocalChannelHandle* handle) override;
 
  private:
+  RecvInterface* receiver_;
   ByteBuffer buffer_;
   std::vector<LocalHandle> file_handles_;
   size_t read_pos_{0};
diff --git a/libs/vr/libvrflinger/compositor.cpp b/libs/vr/libvrflinger/compositor.cpp
index ea05b01..239ef75 100644
--- a/libs/vr/libvrflinger/compositor.cpp
+++ b/libs/vr/libvrflinger/compositor.cpp
@@ -405,6 +405,7 @@
   }
 
   load_gl_extensions();
+  GpuProfiler::Get()->OnGlContextCreated();
 
   glEnable(BINNING_CONTROL_HINT_QCOM);
   glHint(BINNING_CONTROL_HINT_QCOM, RENDER_DIRECT_TO_FRAMEBUFFER_QCOM);
@@ -441,6 +442,7 @@
   eds_renderer_.reset();
 
   if (context_) {
+    GpuProfiler::Get()->OnGlContextDestroyed();
     eglDestroyContext(display_, context_);
     context_ = 0;
   }
diff --git a/libs/vr/libvrflinger/display_service.cpp b/libs/vr/libvrflinger/display_service.cpp
index 5cdb3bb..971345b 100644
--- a/libs/vr/libvrflinger/display_service.cpp
+++ b/libs/vr/libvrflinger/display_service.cpp
@@ -208,17 +208,17 @@
 
   // We should always have a red distortion.
   LOG_FATAL_IF(view_params.distortion_coefficients_r.empty());
-  red_distortion = std::make_shared<PolynomialRadialDistortion>(0.0f,
-      view_params.distortion_coefficients_r);
+  red_distortion = std::make_shared<PolynomialRadialDistortion>(
+      0.0f, view_params.distortion_coefficients_r);
 
   if (!view_params.distortion_coefficients_g.empty()) {
-    green_distortion = std::make_shared<PolynomialRadialDistortion>(0.0f,
-        view_params.distortion_coefficients_g);
+    green_distortion = std::make_shared<PolynomialRadialDistortion>(
+        0.0f, view_params.distortion_coefficients_g);
   }
 
   if (!view_params.distortion_coefficients_b.empty()) {
-    blue_distortion = std::make_shared<PolynomialRadialDistortion>(0.0f,
-        view_params.distortion_coefficients_b);
+    blue_distortion = std::make_shared<PolynomialRadialDistortion>(
+        0.0f, view_params.distortion_coefficients_b);
   }
 
   HeadMountMetrics::EyeOrientation left_orientation =
@@ -331,11 +331,9 @@
     int consumer_usage) {
   auto named_buffer = named_buffers_.find(name);
   if (named_buffer == named_buffers_.end()) {
-    // TODO(hendrikw): Update BufferProducer to take producer_usage and
-    // consumer_usage flags.
     auto ion_buffer = std::make_unique<IonBuffer>(
-        static_cast<int>(size), 1, HAL_PIXEL_FORMAT_BLOB,
-        producer_usage | consumer_usage);
+        static_cast<int>(size), 1, HAL_PIXEL_FORMAT_BLOB, producer_usage,
+        consumer_usage);
     named_buffer =
         named_buffers_.insert(std::make_pair(name, std::move(ion_buffer)))
             .first;
diff --git a/opengl/libs/EGL/eglApi.cpp b/opengl/libs/EGL/eglApi.cpp
index 0807d1f..9de15d0 100644
--- a/opengl/libs/EGL/eglApi.cpp
+++ b/opengl/libs/EGL/eglApi.cpp
@@ -223,6 +223,10 @@
             (__eglMustCastToProperFunctionPointerType)&eglGetFrameTimestampsANDROID },
     { "eglGetFrameTimestampSupportedANDROID",
             (__eglMustCastToProperFunctionPointerType)&eglGetFrameTimestampSupportedANDROID },
+
+    // EGL_ANDROID_native_fence_sync
+    { "eglDupNativeFenceFDANDROID",
+            (__eglMustCastToProperFunctionPointerType)&eglDupNativeFenceFDANDROID },
 };
 
 /*
@@ -232,8 +236,7 @@
 #define FILTER_EXTENSIONS(procname) \
         (!strcmp((procname), "eglSetBlobCacheFuncsANDROID") ||    \
          !strcmp((procname), "eglHibernateProcessIMG")      ||    \
-         !strcmp((procname), "eglAwakenProcessIMG")         ||    \
-         !strcmp((procname), "eglDupNativeFenceFDANDROID"))
+         !strcmp((procname), "eglAwakenProcessIMG"))
 
 
 
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index 5e5efb7..d044f37 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -2617,6 +2617,21 @@
     const auto& p = getParent();
     if (p != nullptr) {
         t = p->getTransform();
+
+        // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
+        // it isFixedSize) then there may be additional scaling not accounted
+        // for in the transform. We need to mirror this scaling in child surfaces
+        // or we will break the contract where WM can treat child surfaces as
+        // pixels in the parent surface.
+        if (p->isFixedSize()) {
+            float sx = p->getDrawingState().active.w /
+                    static_cast<float>(p->mActiveBuffer->getWidth());
+            float sy = p->getDrawingState().active.h /
+                    static_cast<float>(p->mActiveBuffer->getHeight());
+            Transform extraParentScaling;
+            extraParentScaling.set(sx, 0, 0, sy);
+            t = t * extraParentScaling;
+        }
     }
     return t * getDrawingState().active.transform;
 }
diff --git a/services/surfaceflinger/tests/Transaction_test.cpp b/services/surfaceflinger/tests/Transaction_test.cpp
index 441fc7e..7a8b4ab 100644
--- a/services/surfaceflinger/tests/Transaction_test.cpp
+++ b/services/surfaceflinger/tests/Transaction_test.cpp
@@ -909,4 +909,36 @@
     }
 }
 
+TEST_F(ChildLayerTest, ChildrenInheritNonTransformScalingFromParent) {
+    SurfaceComposerClient::openGlobalTransaction();
+    mChild->show();
+    mChild->setPosition(0, 0);
+    mFGSurfaceControl->setPosition(0, 0);
+    SurfaceComposerClient::closeGlobalTransaction(true);
+
+    {
+        ScreenCapture::captureScreen(&mCapture);
+        // We've positioned the child in the top left.
+        mCapture->expectChildColor(0, 0);
+        // But it's only 10x10.
+        mCapture->expectFGColor(10, 10);
+    }
+
+    SurfaceComposerClient::openGlobalTransaction();
+    mFGSurfaceControl->setOverrideScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
+    // We cause scaling by 2.
+    mFGSurfaceControl->setSize(128, 128);
+    SurfaceComposerClient::closeGlobalTransaction();
+
+    {
+        ScreenCapture::captureScreen(&mCapture);
+        // We've positioned the child in the top left.
+        mCapture->expectChildColor(0, 0);
+        mCapture->expectChildColor(10, 10);
+        mCapture->expectChildColor(19, 19);
+        // And now it should be scaled all the way to 20x20
+        mCapture->expectFGColor(20, 20);
+    }
+}
+
 }
diff --git a/services/vr/hardware_composer/Android.bp b/services/vr/hardware_composer/Android.bp
index b94d333..25bb30b 100644
--- a/services/vr/hardware_composer/Android.bp
+++ b/services/vr/hardware_composer/Android.bp
@@ -1,3 +1,51 @@
+cc_library_shared {
+  name: "libvr_hwc-hal",
+
+  srcs: [
+    "impl/vr_hwc.cpp",
+    "impl/vr_composer_client.cpp",
+  ],
+
+  static_libs: [
+    "libhwcomposer-client",
+    "libdisplay",
+    "libbufferhubqueue",
+    "libbufferhub",
+    "libpdx_default_transport",
+  ],
+
+  shared_libs: [
+    "android.frameworks.vr.composer@1.0",
+    "android.hardware.graphics.composer@2.1",
+    "libbase",
+    "libcutils",
+    "libfmq",
+    "libhardware",
+    "libhidlbase",
+    "libhidltransport",
+    "liblog",
+    "libsync",
+    "libui",
+    "libutils",
+  ],
+
+  export_static_lib_headers: [
+    "libhwcomposer-client",
+  ],
+
+  export_shared_lib_headers: [
+    "android.frameworks.vr.composer@1.0",
+    "android.hardware.graphics.composer@2.1",
+  ],
+
+  export_include_dirs: ["."],
+
+  cflags: [
+    "-DLOG_TAG=\"vr_hwc\"",
+  ],
+
+}
+
 cc_library_static {
   name: "libvr_hwc-binder",
   srcs: [
@@ -12,11 +60,12 @@
     export_aidl_headers: true,
   },
   export_include_dirs: ["aidl"],
+
   shared_libs: [
     "libbinder",
     "libui",
     "libutils",
-    "libvrhwc",
+    "libvr_hwc-hal",
   ],
 }
 
@@ -34,10 +83,10 @@
     "liblog",
     "libui",
     "libutils",
-    "libvrhwc",
+    "libvr_hwc-hal",
   ],
   export_shared_lib_headers: [
-    "libvrhwc",
+    "libvr_hwc-hal",
   ],
   cflags: [
     "-DLOG_TAG=\"vr_hwc\"",
@@ -65,7 +114,7 @@
     "libhwbinder",
     "libui",
     "libutils",
-    "libvrhwc",
+    "libvr_hwc-hal",
   ],
   cflags: [
     "-DLOG_TAG=\"vr_hwc\"",
diff --git a/services/vr/vr_window_manager/composer/impl/vr_composer_client.cpp b/services/vr/hardware_composer/impl/vr_composer_client.cpp
similarity index 97%
rename from services/vr/vr_window_manager/composer/impl/vr_composer_client.cpp
rename to services/vr/hardware_composer/impl/vr_composer_client.cpp
index e0bdf1c..ae54e56 100644
--- a/services/vr/vr_window_manager/composer/impl/vr_composer_client.cpp
+++ b/services/vr/hardware_composer/impl/vr_composer_client.cpp
@@ -19,8 +19,8 @@
 #include <hardware/gralloc1.h>
 #include <log/log.h>
 
-#include "vr_hwc.h"
-#include "vr_composer_client.h"
+#include "impl/vr_hwc.h"
+#include "impl/vr_composer_client.h"
 
 namespace android {
 namespace dvr {
diff --git a/services/vr/vr_window_manager/composer/impl/vr_composer_client.h b/services/vr/hardware_composer/impl/vr_composer_client.h
similarity index 90%
rename from services/vr/vr_window_manager/composer/impl/vr_composer_client.h
rename to services/vr/hardware_composer/impl/vr_composer_client.h
index 8d601ab..1236be9 100644
--- a/services/vr/vr_window_manager/composer/impl/vr_composer_client.h
+++ b/services/vr/hardware_composer/impl/vr_composer_client.h
@@ -14,8 +14,8 @@
  * limitations under the License.
  */
 
-#ifndef VR_WINDOW_MANAGER_COMPOSER_IMPL_VR_COMPOSER_CLIENT_H_
-#define VR_WINDOW_MANAGER_COMPOSER_IMPL_VR_COMPOSER_CLIENT_H_
+#ifndef ANDROID_DVR_HARDWARE_COMPOSER_IMPL_VR_COMPOSER_CLIENT_H
+#define ANDROID_DVR_HARDWARE_COMPOSER_IMPL_VR_COMPOSER_CLIENT_H
 
 #include <android/frameworks/vr/composer/1.0/IVrComposerClient.h>
 #include <ComposerClient.h>
@@ -68,4 +68,4 @@
 } // namespace dvr
 } // namespace android
 
-#endif  // VR_WINDOW_MANAGER_COMPOSER_IMPL_VR_COMPOSER_CLIENT_H_
+#endif  // ANDROID_DVR_HARDWARE_COMPOSER_IMPL_VR_COMPOSER_CLIENT_H
diff --git a/services/vr/vr_window_manager/composer/impl/vr_hwc.cpp b/services/vr/hardware_composer/impl/vr_hwc.cpp
similarity index 99%
rename from services/vr/vr_window_manager/composer/impl/vr_hwc.cpp
rename to services/vr/hardware_composer/impl/vr_hwc.cpp
index f5d88f2..29983a7 100644
--- a/services/vr/vr_window_manager/composer/impl/vr_hwc.cpp
+++ b/services/vr/hardware_composer/impl/vr_hwc.cpp
@@ -13,14 +13,13 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#include "vr_hwc.h"
+#include "impl/vr_hwc.h"
 
+#include <private/dvr/display_client.h>
 #include <ui/Fence.h>
 
 #include <mutex>
 
-#include <private/dvr/display_client.h>
-
 #include "vr_composer_client.h"
 
 using namespace android::hardware::graphics::common::V1_0;
diff --git a/services/vr/vr_window_manager/composer/impl/vr_hwc.h b/services/vr/hardware_composer/impl/vr_hwc.h
similarity index 98%
rename from services/vr/vr_window_manager/composer/impl/vr_hwc.h
rename to services/vr/hardware_composer/impl/vr_hwc.h
index 609d925..df04208 100644
--- a/services/vr/vr_window_manager/composer/impl/vr_hwc.h
+++ b/services/vr/hardware_composer/impl/vr_hwc.h
@@ -13,8 +13,8 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#ifndef VR_WINDOW_MANAGER_COMPOSER_IMPL_VR_HWC_H_
-#define VR_WINDOW_MANAGER_COMPOSER_IMPL_VR_HWC_H_
+#ifndef ANDROID_DVR_HARDWARE_COMPOSER_IMPL_VR_HWC_H
+#define ANDROID_DVR_HARDWARE_COMPOSER_IMPL_VR_HWC_H
 
 #include <android-base/unique_fd.h>
 #include <android/frameworks/vr/composer/1.0/IVrComposerClient.h>
@@ -319,4 +319,4 @@
 }  // namespace dvr
 }  // namespace android
 
-#endif  // VR_WINDOW_MANAGER_COMPOSER_IMPL_VR_HWC_H_
+#endif  // ANDROID_DVR_HARDWARE_COMPOSER_IMPL_VR_HWC_H
diff --git a/services/vr/vr_window_manager/Android.bp b/services/vr/vr_window_manager/Android.bp
index 669426b..d7ddba1 100644
--- a/services/vr/vr_window_manager/Android.bp
+++ b/services/vr/vr_window_manager/Android.bp
@@ -12,8 +12,6 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-subdirs = [ "composer", ]
-
 native_src = [
     "application.cpp",
     "controller_mesh.cpp",
@@ -49,7 +47,6 @@
 shared_libs = [
     "android.frameworks.vr.composer@1.0",
     "android.hardware.graphics.composer@2.1",
-    "libvrhwc",
     "libbase",
     "libbinder",
     "libinput",
@@ -66,6 +63,7 @@
     "libhidlbase",
     "libhidltransport",
     "liblog",
+    "libvr_hwc-hal",
 ]
 
 cc_binary {
diff --git a/services/vr/vr_window_manager/composer/Android.bp b/services/vr/vr_window_manager/composer/Android.bp
deleted file mode 100644
index 1998749..0000000
--- a/services/vr/vr_window_manager/composer/Android.bp
+++ /dev/null
@@ -1,47 +0,0 @@
-cc_library_shared {
-  name: "libvrhwc",
-
-  srcs: [
-    "impl/vr_composer_view.cpp",
-    "impl/vr_hwc.cpp",
-    "impl/vr_composer_client.cpp",
-  ],
-
-  static_libs: [
-    "libhwcomposer-client",
-    "libdisplay",
-    "libbufferhubqueue",
-    "libbufferhub",
-    "libpdx_default_transport",
-  ],
-
-  shared_libs: [
-    "android.frameworks.vr.composer@1.0",
-    "android.hardware.graphics.composer@2.1",
-    "libbase",
-    "libcutils",
-    "libfmq",
-    "libhardware",
-    "libhidlbase",
-    "libhidltransport",
-    "liblog",
-    "libsync",
-    "libui",
-    "libutils",
-  ],
-
-  export_static_lib_headers: [
-    "libhwcomposer-client",
-  ],
-
-  export_shared_lib_headers: [
-    "android.frameworks.vr.composer@1.0",
-    "android.hardware.graphics.composer@2.1",
-  ],
-
-  export_include_dirs: ["."],
-
-  cflags: [
-    "-DLOG_TAG=\"vrhwc\"",
-  ],
-}
diff --git a/services/vr/vr_window_manager/composer/impl/vr_composer_view.cpp b/services/vr/vr_window_manager/composer/impl/vr_composer_view.cpp
deleted file mode 100644
index 299e8f1..0000000
--- a/services/vr/vr_window_manager/composer/impl/vr_composer_view.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include "vr_composer_view.h"
-
-namespace android {
-namespace dvr {
-
-VrComposerView::VrComposerView(
-    std::unique_ptr<VrComposerView::Callback> callback)
-    : composer_view_(nullptr), callback_(std::move(callback)) {}
-
-VrComposerView::~VrComposerView() {
-  composer_view_->UnregisterObserver(this);
-}
-
-void VrComposerView::Initialize(ComposerView* composer_view) {
-  composer_view_ = composer_view;
-  composer_view_->RegisterObserver(this);
-}
-
-base::unique_fd VrComposerView::OnNewFrame(const ComposerView::Frame& frame) {
-  std::lock_guard<std::mutex> guard(mutex_);
-  if (!callback_.get())
-    return base::unique_fd();
-
-  return callback_->OnNewFrame(frame);
-}
-
-}  // namespace dvr
-}  // namespace android
diff --git a/services/vr/vr_window_manager/composer/impl/vr_composer_view.h b/services/vr/vr_window_manager/composer/impl/vr_composer_view.h
deleted file mode 100644
index 8c5ee1f..0000000
--- a/services/vr/vr_window_manager/composer/impl/vr_composer_view.h
+++ /dev/null
@@ -1,36 +0,0 @@
-#ifndef VR_WINDOW_MANAGER_COMPOSER_IMPL_VR_COMPOSER_VIEW_H_
-#define VR_WINDOW_MANAGER_COMPOSER_IMPL_VR_COMPOSER_VIEW_H_
-
-#include <memory>
-
-#include "vr_hwc.h"
-
-namespace android {
-namespace dvr {
-
-class VrComposerView : public ComposerView::Observer {
- public:
-  class Callback {
-   public:
-    virtual ~Callback() = default;
-    virtual base::unique_fd OnNewFrame(const ComposerView::Frame& frame) = 0;
-  };
-
-  VrComposerView(std::unique_ptr<Callback> callback);
-  ~VrComposerView() override;
-
-  void Initialize(ComposerView* composer_view);
-
-  // ComposerView::Observer
-  base::unique_fd OnNewFrame(const ComposerView::Frame& frame) override;
-
- private:
-  ComposerView* composer_view_;
-  std::unique_ptr<Callback> callback_;
-  std::mutex mutex_;
-};
-
-}  // namespace dvr
-}  // namespace android
-
-#endif  // VR_WINDOW_MANAGER_COMPOSER_IMPL_VR_COMPOSER_VIEW_H_
diff --git a/services/vr/vr_window_manager/composer_view/Android.bp_disable b/services/vr/vr_window_manager/composer_view/Android.bp_disable
deleted file mode 100644
index 1658154..0000000
--- a/services/vr/vr_window_manager/composer_view/Android.bp_disable
+++ /dev/null
@@ -1,29 +0,0 @@
-cc_binary {
-  name: "vr_composer_view",
-
-  srcs: ["vr_composer_view.cpp"],
-
-  static_libs: [
-    "libhwcomposer-client",
-  ],
-
-  shared_libs: [
-    "android.dvr.composer@1.0",
-    "android.hardware.graphics.composer@2.1",
-    "libbase",
-    "libbinder",
-    "libhardware",
-    "libhwbinder",
-    "liblog",
-    "libutils",
-    "libvrhwc",
-  ],
-
-  cflags: [
-    "-DLOG_TAG=\"vr_composer_view\"",
-  ],
-
-  init_rc: [
-    "vr_composer_view.rc",
-  ],
-}
diff --git a/services/vr/vr_window_manager/composer_view/vr_composer_view.cpp b/services/vr/vr_window_manager/composer_view/vr_composer_view.cpp
deleted file mode 100644
index 54dff3d..0000000
--- a/services/vr/vr_window_manager/composer_view/vr_composer_view.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include <binder/ProcessState.h>
-#include <hwbinder/IPCThreadState.h>
-#include <impl/vr_composer_view.h>
-#include <impl/vr_hwc.h>
-
-using namespace android;
-using namespace android::dvr;
-
-int main(int, char**) {
-  android::ProcessState::self()->startThreadPool();
-
-  const char instance[] = "vr_hwcomposer";
-  sp<IComposer> service = HIDL_FETCH_IComposer(instance);
-  LOG_ALWAYS_FATAL_IF(!service.get(), "Failed to get service");
-  LOG_ALWAYS_FATAL_IF(service->isRemote(), "Service is remote");
-
-  LOG_ALWAYS_FATAL_IF(service->registerAsService(instance) != ::android::OK,
-                      "Failed to register service");
-
-  sp<IVrComposerView> composer_view = HIDL_FETCH_IVrComposerView(
-      "DaydreamDisplay");
-  LOG_ALWAYS_FATAL_IF(!composer_view.get(),
-                      "Failed to get vr_composer_view service");
-  LOG_ALWAYS_FATAL_IF(composer_view->isRemote(),
-                      "vr_composer_view service is remote");
-
-  composer_view->registerAsService("DaydreamDisplay");
-
-  GetVrComposerViewFromIVrComposerView(composer_view.get())->Initialize(
-      GetComposerViewFromIComposer(service.get()));
-
-  android::hardware::ProcessState::self()->startThreadPool();
-  android::hardware::IPCThreadState::self()->joinThreadPool();
-
-  return 0;
-}
diff --git a/services/vr/vr_window_manager/composer_view/vr_composer_view.rc b/services/vr/vr_window_manager/composer_view/vr_composer_view.rc
deleted file mode 100644
index bd9982b..0000000
--- a/services/vr/vr_window_manager/composer_view/vr_composer_view.rc
+++ /dev/null
@@ -1,5 +0,0 @@
-service vr_composer_view /system/bin/vr_composer_view
-  class core
-  user system
-  group system graphics
-  writepid /dev/cpuset/system/tasks
diff --git a/services/vr/vr_window_manager/hwc_callback.h b/services/vr/vr_window_manager/hwc_callback.h
index 4269430..259c4ac 100644
--- a/services/vr/vr_window_manager/hwc_callback.h
+++ b/services/vr/vr_window_manager/hwc_callback.h
@@ -3,15 +3,13 @@
 
 #include <android/dvr/BnVrComposerCallback.h>
 #include <android-base/unique_fd.h>
+#include <impl/vr_hwc.h>
 
 #include <deque>
 #include <functional>
 #include <mutex>
 #include <vector>
 
-#include "impl/vr_composer_view.h"
-#include "impl/vr_hwc.h"
-
 namespace android {
 
 class Fence;
diff --git a/services/vr/vr_window_manager/surface_flinger_view.cpp b/services/vr/vr_window_manager/surface_flinger_view.cpp
index aef23a1..b41de03 100644
--- a/services/vr/vr_window_manager/surface_flinger_view.cpp
+++ b/services/vr/vr_window_manager/surface_flinger_view.cpp
@@ -2,7 +2,6 @@
 
 #include <android/dvr/IVrComposer.h>
 #include <binder/IServiceManager.h>
-#include <impl/vr_composer_view.h>
 #include <private/dvr/native_buffer.h>
 
 #include "hwc_callback.h"
diff --git a/services/vr/vr_window_manager/vr_window_manager.cpp b/services/vr/vr_window_manager/vr_window_manager.cpp
index 9d7afe3..dd2cba7 100644
--- a/services/vr/vr_window_manager/vr_window_manager.cpp
+++ b/services/vr/vr_window_manager/vr_window_manager.cpp
@@ -2,7 +2,6 @@
 #include <binder/IServiceManager.h>
 #include <binder/ProcessState.h>
 #include <hwbinder/IPCThreadState.h>
-#include <impl/vr_composer_view.h>
 #include <impl/vr_hwc.h>
 
 #include "shell_view.h"