Emulator: update opengl to bb8d138b
am: 1b5d5a70fe  -s ours

Change-Id: I98ded2d9ba13cc01051cc42352498b8dc4469da6
diff --git a/Android.mk b/Android.mk
index 9061c9b..31db4f2 100644
--- a/Android.mk
+++ b/Android.mk
@@ -24,6 +24,14 @@
 #
 EMUGL_COMMON_CFLAGS := -DWITH_GLES2 -DPLATFORM_SDK_VERSION=$(PLATFORM_SDK_VERSION)
 
+ifeq (O, $(PLATFORM_VERSION_CODENAME))
+    EMUGL_COMMON_CFLAGS += -DGOLDFISH_HIDL_GRALLOC
+endif
+
+ifdef IS_AT_LEAST_OPD1
+    EMUGL_COMMON_CFLAGS += -DEMULATOR_OPENGL_POST_O=1
+endif
+
 ifeq ($(shell test $(PLATFORM_SDK_VERSION) -lt 18 && echo PreJellyBeanMr2),PreJellyBeanMr2)
     ifeq ($(ARCH_ARM_HAVE_TLS_REGISTER),true)
         EMUGL_COMMON_CFLAGS += -DHAVE_ARM_TLS_REGISTER
@@ -73,7 +81,6 @@
 include $(EMUGL_PATH)/system/GLESv2/Android.mk
 
 include $(EMUGL_PATH)/system/gralloc/Android.mk
-include $(EMUGL_PATH)/system/surfaceInterface/Android.mk
 include $(EMUGL_PATH)/system/egl/Android.mk
 
 endif # BUILD_EMULATOR_OPENGL == true
diff --git a/common.mk b/common.mk
index 67e9284..c15812e 100644
--- a/common.mk
+++ b/common.mk
@@ -38,6 +38,10 @@
     $(eval _EMUGL_INCLUDE_TYPE := $(BUILD_$2)) \
     $(call _emugl-init-module,$1,$2,$3)
 
+ifeq ($(shell test $(PLATFORM_SDK_VERSION) -ge 26 && echo TREBLE),TREBLE)
+    emugl-begin-module += $(eval LOCAL_VENDOR_MODULE := true)
+endif
+
 ifeq ($(shell test $(PLATFORM_SDK_VERSION) -lt 23 && echo PreMarshmallow),PreMarshmallow)
     emugl-begin-module += $(eval include external/stlport/libstlport.mk)
 endif
@@ -102,6 +106,10 @@
     STATIC_LIBRARIES \
     ADDITIONAL_DEPENDENCIES
 
+ifdef IS_AT_LEAST_OPD1
+EMUGL_EXPORT_TYPES += HEADER_LIBRARIES
+endif
+
 # Initialize a module in our database
 # $1: Module name
 # $2: Module type
diff --git a/system/GLESv2_enc/GL2Encoder.cpp b/system/GLESv2_enc/GL2Encoder.cpp
index 66b9e19..3c37a82 100755
--- a/system/GLESv2_enc/GL2Encoder.cpp
+++ b/system/GLESv2_enc/GL2Encoder.cpp
@@ -2095,9 +2095,16 @@
 void GL2Encoder::restore2DTextureTarget(GLenum target)
 {
     if (texture2DNeedsOverride(target)) {
-        m_glBindTexture_enc(this, GL_TEXTURE_2D,
+        GLuint priorityEnabledBoundTexture =
                 m_state->getBoundTexture(
-                    m_state->getPriorityEnabledTarget(GL_TEXTURE_2D)));
+                    m_state->getPriorityEnabledTarget(GL_TEXTURE_2D));
+        GLuint texture2DBoundTexture =
+                m_state->getBoundTexture(GL_TEXTURE_2D);
+        if (!priorityEnabledBoundTexture) {
+            m_glBindTexture_enc(this, GL_TEXTURE_2D, texture2DBoundTexture);
+        } else {
+            m_glBindTexture_enc(this, GL_TEXTURE_2D, priorityEnabledBoundTexture);
+        }
     }
 }
 
diff --git a/system/OpenglSystemCommon/Android.mk b/system/OpenglSystemCommon/Android.mk
index b585971..9305119 100644
--- a/system/OpenglSystemCommon/Android.mk
+++ b/system/OpenglSystemCommon/Android.mk
@@ -5,13 +5,23 @@
 
 LOCAL_SRC_FILES := \
     goldfish_dma.cpp \
-    goldfishHwc2.cpp \
     FormatConversions.cpp \
     HostConnection.cpp \
     ProcessPipe.cpp    \
     QemuPipeStream.cpp \
     ThreadInfo.cpp
 
+ifdef IS_AT_LEAST_OPD1
+LOCAL_HEADER_LIBRARIES += libnativebase_headers
+
+$(call emugl-export,HEADER_LIBRARIES,libnativebase_headers)
+endif
+
+ifdef IS_AT_LEAST_OPD1
+LOCAL_HEADER_LIBRARIES += libhardware_headers
+$(call emugl-export,HEADER_LIBRARIES,libhardware_headers)
+endif
+
 $(call emugl-export,C_INCLUDES,$(LOCAL_PATH) bionic/libc/private)
 
 $(call emugl-end-module)
diff --git a/system/OpenglSystemCommon/EGLImage.h b/system/OpenglSystemCommon/EGLImage.h
index 9f8f901..6cb7431 100644
--- a/system/OpenglSystemCommon/EGLImage.h
+++ b/system/OpenglSystemCommon/EGLImage.h
@@ -21,7 +21,10 @@
 #include <GLES/gl.h>
 
 #if PLATFORM_SDK_VERSION >= 16
-#include <system/window.h>
+#if EMULATOR_OPENGL_POST_O >= 1
+#include <nativebase/nativebase.h>
+#endif
+#include <cutils/native_handle.h>
 #else // PLATFORM_SDK_VERSION >= 16
 #include <private/ui/android_natives_priv.h>
 #endif // PLATFORM_SDK_VERSION >= 16
diff --git a/system/OpenglSystemCommon/goldfishHwc2.cpp b/system/OpenglSystemCommon/goldfishHwc2.cpp
deleted file mode 100644
index 888ba89..0000000
--- a/system/OpenglSystemCommon/goldfishHwc2.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
-* Copyright (C) 2017 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-#include "goldfishHwc2.h"
-
-// Stub functions if not using HWC2.
-#ifndef USE_HWC2
-extern "C" void surfaceInterface_init() { }
-extern "C" void surfaceInterface_setAsyncModeForWindow(void* window) { }
-#endif
diff --git a/system/OpenglSystemCommon/goldfishHwc2.h b/system/OpenglSystemCommon/goldfishHwc2.h
deleted file mode 100644
index cb1a396..0000000
--- a/system/OpenglSystemCommon/goldfishHwc2.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
-* Copyright (C) 2017 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-#pragma once
-
-// Set of functions that help support HWC2 in the emulator.
-
-#ifdef USE_HWC2
-#include "../surfaceInterface/surfaceInterface.h"
-#else
-extern "C" void surfaceInterface_init();
-extern "C" void surfaceInterface_setAsyncModeForWindow(void* window);
-#endif
diff --git a/system/egl/Android.mk b/system/egl/Android.mk
index 37aadd7..2d7a559 100644
--- a/system/egl/Android.mk
+++ b/system/egl/Android.mk
@@ -13,12 +13,17 @@
     egl.cpp \
     ClientAPIExts.cpp
 
-ifeq ($(TARGET_USES_HWC2), true)
-    LOCAL_CFLAGS += -DUSE_HWC2
-    LOCAL_STATIC_LIBRARIES += libsurfaceInterface
+ifdef IS_AT_LEAST_OPD1
+LOCAL_SHARED_LIBRARIES += libdl libnativewindow
+else
+LOCAL_SHARED_LIBRARIES += libdl
 endif
 
-LOCAL_SHARED_LIBRARIES += libdl
+ifdef IS_AT_LEAST_OPD1
+LOCAL_SHARED_LIBRARIES += libui
+LOCAL_HEADER_LIBRARIES += libnativebase_headers
+endif
+
 # Used to access the Bionic private OpenGL TLS slot
 LOCAL_C_INCLUDES += bionic/libc/private
 
diff --git a/system/egl/egl.cpp b/system/egl/egl.cpp
index b22e116..66a8a45 100644
--- a/system/egl/egl.cpp
+++ b/system/egl/egl.cpp
@@ -29,7 +29,6 @@
 #include "eglContext.h"
 #include "ClientAPIExts.h"
 #include "EGLImage.h"
-#include "goldfishHwc2.h"
 #include "ProcessPipe.h"
 
 #include "GLEncoder.h"
@@ -39,6 +38,10 @@
 
 #include <GLES3/gl31.h>
 
+#if PLATFORM_SDK_VERSION < 18
+#define override
+#endif
+
 #if PLATFORM_SDK_VERSION >= 16
 #include <system/window.h>
 #else // PLATFORM_SDK_VERSION >= 16
@@ -171,6 +174,11 @@
 // The one and only supported display object.
 static eglDisplay s_display;
 
+// Extra defines not in the official EGL spec yet,
+// but required in Android CTS.
+
+#define EGL_TIMESTAMPS_ANDROID 0x314D
+
 EGLContext_t::EGLContext_t(EGLDisplay dpy, EGLConfig config, EGLContext_t* shareCtx, int maj, int min) :
     dpy(dpy),
     config(config),
@@ -181,7 +189,7 @@
     versionString(NULL),
     majorVersion(maj),
     minorVersion(min),
-    vendorString(NULL),
+    vendorString(NULL) ,
     rendererString(NULL),
     shaderVersionString(NULL),
     extensionString(NULL),
@@ -272,6 +280,9 @@
     void        setTextureTarget(EGLint _texTarget) { texTarget = _texTarget; }
     EGLint      getTextureTarget() { return texTarget; }
 
+    virtual     void setCollectingTimestamps(EGLint collect) { }
+    virtual     EGLint isCollectingTimestamps() const { return EGL_FALSE; }
+
 private:
     //
     //Surface attributes
@@ -333,6 +344,11 @@
     virtual void       setSwapInterval(int interval);
     virtual EGLBoolean swapBuffers();
 
+    virtual     void        setCollectingTimestamps(EGLint collect)
+        override { collectingTimestamps = (collect == EGL_TRUE) ? true : false; }
+    virtual     EGLint isCollectingTimestamps() const override { return collectingTimestamps ? EGL_TRUE : EGL_FALSE; }
+
+
 private:
     egl_window_surface_t(
             EGLDisplay dpy, EGLConfig config, EGLint surfType,
@@ -341,6 +357,7 @@
 
     ANativeWindow*              nativeWindow;
     android_native_buffer_t*    buffer;
+    bool collectingTimestamps;
 };
 
 egl_window_surface_t::egl_window_surface_t (
@@ -348,7 +365,8 @@
         ANativeWindow* window)
 :   egl_surface_t(dpy, config, surfType),
     nativeWindow(window),
-    buffer(NULL)
+    buffer(NULL),
+    collectingTimestamps(false)
 {
     // keep a reference on the window
     nativeWindow->common.incRef(&nativeWindow->common);
@@ -380,8 +398,6 @@
     rcEnc->rcSetWindowColorBuffer(rcEnc, rcSurface,
             ((cb_handle_t*)(buffer->handle))->hostHandle);
 
-    surfaceInterface_setAsyncModeForWindow((void*)nativeWindow);
-
     return EGL_TRUE;
 }
 
@@ -1097,6 +1113,9 @@
             // ignored when creating the surface, return default
             *value = EGL_VG_ALPHA_FORMAT_NONPRE;
             break;
+        case EGL_TIMESTAMPS_ANDROID:
+            *value = surface->isCollectingTimestamps();
+            break;
         //TODO: complete other attributes
         default:
             ALOGE("eglQuerySurface %x  EGL_BAD_ATTRIBUTE", attribute);
@@ -1189,7 +1208,6 @@
     switch (attribute) {
     case EGL_MIPMAP_LEVEL:
         return true;
-        break;
     case EGL_MULTISAMPLE_RESOLVE:
     {
         if (value == EGL_MULTISAMPLE_RESOLVE_BOX) {
@@ -1200,7 +1218,6 @@
             }
         }
         return true;
-        break;
     }
     case EGL_SWAP_BEHAVIOR:
         if (value == EGL_BUFFER_PRESERVED) {
@@ -1211,7 +1228,10 @@
             }
         }
         return true;
-        break;
+    case EGL_TIMESTAMPS_ANDROID:
+        ALOGD("%s: set frame timestamps collecting %d\n", __func__, value);
+        p_surface->setCollectingTimestamps(value);
+        return true;
     default:
         ALOGW("%s: attr=0x%x not implemented", __FUNCTION__, attribute);
         setErrorReturn(EGL_BAD_ATTRIBUTE, EGL_FALSE);
diff --git a/system/egl/eglDisplay.cpp b/system/egl/eglDisplay.cpp
index 890eb50..c7ff179 100644
--- a/system/egl/eglDisplay.cpp
+++ b/system/egl/eglDisplay.cpp
@@ -15,8 +15,6 @@
 */
 #include "eglDisplay.h"
 #include "HostConnection.h"
-#include "goldfishHwc2.h"
-
 #include <dlfcn.h>
 
 #include <string>
@@ -72,7 +70,6 @@
     pthread_mutex_init(&m_lock, NULL);
     pthread_mutex_init(&m_ctxLock, NULL);
     pthread_mutex_init(&m_surfaceLock, NULL);
-    surfaceInterface_init();
 }
 
 eglDisplay::~eglDisplay()
@@ -83,6 +80,12 @@
     pthread_mutex_destroy(&m_surfaceLock);
 }
 
+#if PLATFORM_SDK_VERSION >= 26
+#define PARTITION "/vendor"
+#else
+#define PARTITION "/system"
+#endif
+
 bool eglDisplay::initialize(EGLClient_eglInterface *eglIface)
 {
     pthread_mutex_lock(&m_lock);
@@ -92,11 +95,11 @@
         // load GLES client API
         //
 #if __LP64__
-        m_gles_iface = loadGLESClientAPI("/system/lib64/egl/libGLESv1_CM_emulation.so",
+        m_gles_iface = loadGLESClientAPI(PARTITION "/lib64/egl/libGLESv1_CM_emulation.so",
                                          eglIface,
                                          &s_gles_lib);
 #else
-        m_gles_iface = loadGLESClientAPI("/system/lib/egl/libGLESv1_CM_emulation.so",
+        m_gles_iface = loadGLESClientAPI(PARTITION "/lib/egl/libGLESv1_CM_emulation.so",
                                          eglIface,
                                          &s_gles_lib);
 #endif
@@ -108,11 +111,11 @@
 
 #ifdef WITH_GLES2
 #if __LP64__
-        m_gles2_iface = loadGLESClientAPI("/system/lib64/egl/libGLESv2_emulation.so",
+        m_gles2_iface = loadGLESClientAPI(PARTITION "/lib64/egl/libGLESv2_emulation.so",
                                           eglIface,
                                           &s_gles2_lib);
 #else
-        m_gles2_iface = loadGLESClientAPI("/system/lib/egl/libGLESv2_emulation.so",
+        m_gles2_iface = loadGLESClientAPI(PARTITION "/lib/egl/libGLESv2_emulation.so",
                                           eglIface,
                                           &s_gles2_lib);
 #endif
diff --git a/system/egl/goldfish_sync.h b/system/egl/goldfish_sync.h
index 4667a77..6b30fe5 100644
--- a/system/egl/goldfish_sync.h
+++ b/system/egl/goldfish_sync.h
@@ -18,6 +18,10 @@
 #include <linux/ioctl.h>
 #include <linux/types.h>
 #include <sys/cdefs.h>
+#ifdef EMULATOR_OPENGL_POST_O
+#include <sys/ioctl.h>
+#include <sys/unistd.h>
+#endif
 #include <fcntl.h>
 
 // Make it conflict with ioctls that are not likely to be used
diff --git a/system/gralloc/gralloc.cpp b/system/gralloc/gralloc.cpp
index 4e63b00..0b6785e 100644
--- a/system/gralloc/gralloc.cpp
+++ b/system/gralloc/gralloc.cpp
@@ -51,6 +51,23 @@
 
 #define DBG_FUNC DBG("%s\n", __FUNCTION__)
 
+#ifdef GOLDFISH_HIDL_GRALLOC
+static bool isHidlGralloc = true;
+#else
+static bool isHidlGralloc = false;
+#endif
+
+int32_t* getOpenCountPtr(cb_handle_t* cb) {
+    return ((int32_t*)cb->ashmemBase) + 1;
+}
+
+uint32_t getAshmemColorOffset(cb_handle_t* cb) {
+    uint32_t res = 0;
+    if (cb->canBePosted()) res = sizeof(intptr_t);
+    if (isHidlGralloc) res = sizeof(intptr_t) * 2;
+    return res;
+}
+
 //
 // our private gralloc module structure
 //
@@ -262,6 +279,9 @@
         return -EINVAL;
     }
 
+    int map_flags = MAP_SHARED;
+    if (isHidlGralloc) map_flags |= MAP_ANONYMOUS;
+
     void *addr = mmap(0, cb->ashmemSize, PROT_READ | PROT_WRITE,
                       MAP_SHARED, cb->fd, 0);
     if (addr == MAP_FAILED) {
@@ -370,6 +390,15 @@
     if (convertedBuf) delete [] convertedBuf;
 }
 
+#ifndef GL_RGBA16F
+#define GL_RGBA16F                        0x881A
+#endif // GL_RGBA16F
+#ifndef GL_UNSIGNED_INT_10_10_10_2
+#define GL_UNSIGNED_INT_10_10_10_2        0x8DF6
+#endif // GL_UNSIGNED_INT_10_10_10_2
+#ifndef GL_HALF_FLOAT
+#define GL_HALF_FLOAT                     0x140B
+#endif // GL_HALF_FLOAT
 //
 // gralloc device functions (alloc interface)
 //
@@ -469,6 +498,18 @@
             glFormat = GL_RGB;
             glType = GL_UNSIGNED_SHORT_5_6_5;
             break;
+#if PLATFORM_SDK_VERSION >= 26
+        case HAL_PIXEL_FORMAT_RGBA_FP16:
+            bpp = 8;
+            glFormat = GL_RGBA16F;
+            glType = GL_HALF_FLOAT;
+            break;
+        case HAL_PIXEL_FORMAT_RGBA_1010102:
+            bpp = 4;
+            glFormat = GL_RGBA;
+            glType = GL_UNSIGNED_INT_10_10_10_2;
+            break;
+#endif // PLATFORM_SDK_VERSION >= 26
 #if PLATFORM_SDK_VERSION >= 21
         case HAL_PIXEL_FORMAT_RAW16:
         case HAL_PIXEL_FORMAT_Y16:
@@ -488,8 +529,10 @@
 #if PLATFORM_SDK_VERSION >= 17
         case HAL_PIXEL_FORMAT_BLOB:
             bpp = 1;
-            if (! (sw_read && hw_cam_write) ) {
+            if (! (sw_read) ) {
                 // Blob data cannot be used by HW other than camera emulator
+                // But there is a CTS test trying to have access to it
+                // BUG: https://buganizer.corp.google.com/issues/37719518
                 return -EINVAL;
             }
             // Not expecting to actually create any GL surfaces for this
@@ -526,9 +569,39 @@
             return -EINVAL;
     }
 
-    if (usage & GRALLOC_USAGE_HW_FB) {
-        // keep space for postCounter
-        ashmem_size += sizeof(uint32_t);
+    //
+    // Allocate ColorBuffer handle on the host (only if h/w access is allowed)
+    // Only do this for some h/w usages, not all.
+    // Also do this if we need to read from the surface, in this case the
+    // rendering will still happen on the host but we also need to be able to
+    // read back from the color buffer, which requires that there is a buffer
+    //
+    bool needHostCb = (!yuv_format ||
+                       frameworkFormat == HAL_PIXEL_FORMAT_YV12 ||
+                       frameworkFormat == HAL_PIXEL_FORMAT_YCbCr_420_888) &&
+#if PLATFORM_SDK_VERSION >= 15
+                      (usage & (GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_HW_RENDER |
+                                GRALLOC_USAGE_HW_2D | GRALLOC_USAGE_HW_COMPOSER |
+                                GRALLOC_USAGE_HW_VIDEO_ENCODER |
+                                GRALLOC_USAGE_HW_FB | GRALLOC_USAGE_SW_READ_MASK))
+#else // PLATFORM_SDK_VERSION
+                      (usage & (GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_HW_RENDER |
+                                GRALLOC_USAGE_HW_2D |
+                                GRALLOC_USAGE_HW_FB | GRALLOC_USAGE_SW_READ_MASK))
+#endif // PLATFORM_SDK_VERSION
+                      ;
+
+    if (isHidlGralloc) {
+        if (needHostCb || (usage & GRALLOC_USAGE_HW_FB)) {
+            // keep space for postCounter
+            // AND openCounter for all host cb
+            ashmem_size += sizeof(uint32_t) * 2;
+        }
+    } else {
+        if (usage & GRALLOC_USAGE_HW_FB) {
+            // keep space for postCounter
+            ashmem_size += sizeof(uint32_t) * 1;
+        }
     }
 
     if (sw_read || sw_write || hw_cam_write || hw_vid_enc_read) {
@@ -598,43 +671,25 @@
         cb->goldfish_dma.fd = -1;
     }
 
-    //
-    // Allocate ColorBuffer handle on the host (only if h/w access is allowed)
-    // Only do this for some h/w usages, not all.
-    // Also do this if we need to read from the surface, in this case the
-    // rendering will still happen on the host but we also need to be able to
-    // read back from the color buffer, which requires that there is a buffer
-    //
-    if (!yuv_format ||
-        frameworkFormat == HAL_PIXEL_FORMAT_YV12 ||
-        frameworkFormat == HAL_PIXEL_FORMAT_YCbCr_420_888) {
-#if PLATFORM_SDK_VERSION >= 15
-        if (usage & (GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_HW_RENDER |
-                     GRALLOC_USAGE_HW_2D | GRALLOC_USAGE_HW_COMPOSER |
-                     GRALLOC_USAGE_HW_VIDEO_ENCODER |
-                     GRALLOC_USAGE_HW_FB | GRALLOC_USAGE_SW_READ_MASK) ) {
-#else // PLATFORM_SDK_VERSION
-        if (usage & (GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_HW_RENDER |
-                     GRALLOC_USAGE_HW_2D |
-                     GRALLOC_USAGE_HW_FB | GRALLOC_USAGE_SW_READ_MASK) ) {
-#endif // PLATFORM_SDK_VERSION
-            if (hostCon && rcEnc) {
-                if (s_grdma) {
-                    cb->hostHandle = rcEnc->rcCreateColorBufferDMA(rcEnc, w, h, glFormat, cb->emuFrameworkFormat);
-                } else {
-                    cb->hostHandle = rcEnc->rcCreateColorBuffer(rcEnc, w, h, glFormat);
-                }
-                D("Created host ColorBuffer 0x%x\n", cb->hostHandle);
+    if (needHostCb) {
+        if (hostCon && rcEnc) {
+            if (s_grdma) {
+                cb->hostHandle = rcEnc->rcCreateColorBufferDMA(rcEnc, w, h, glFormat, cb->emuFrameworkFormat);
+            } else {
+                cb->hostHandle = rcEnc->rcCreateColorBuffer(rcEnc, w, h, glFormat);
             }
-
-            if (!cb->hostHandle) {
-              // Could not create colorbuffer on host !!!
-              close(fd);
-              delete cb;
-              ALOGD("%s: failed to create host cb! -EIO", __FUNCTION__);
-              return -EIO;
-            }
+            D("Created host ColorBuffer 0x%x\n", cb->hostHandle);
         }
+
+        if (!cb->hostHandle) {
+            // Could not create colorbuffer on host !!!
+            close(fd);
+            delete cb;
+            ALOGD("%s: failed to create host cb! -EIO", __FUNCTION__);
+            return -EIO;
+        }
+
+        if (isHidlGralloc) { *getOpenCountPtr(cb) = 0; }
     }
 
     //
@@ -678,9 +733,19 @@
       __FUNCTION__, handle, cb->ashmemBase, cb->ashmemSize);
 
     if (cb->hostHandle) {
-        DEFINE_AND_VALIDATE_HOST_CONNECTION;
-        D("Closing host ColorBuffer 0x%x\n", cb->hostHandle);
-        rcEnc->rcCloseColorBuffer(rcEnc, cb->hostHandle);
+        int32_t openCount = 1;
+        int32_t* openCountPtr = &openCount;
+
+        if (isHidlGralloc) { openCountPtr = getOpenCountPtr(cb); }
+
+        if (*openCountPtr > 0) {
+            DEFINE_AND_VALIDATE_HOST_CONNECTION;
+            D("Closing host ColorBuffer 0x%x\n", cb->hostHandle);
+            rcEnc->rcCloseColorBuffer(rcEnc, cb->hostHandle);
+        } else {
+            D("A rcCloseColorBuffer is owed!!! sdk ver: %d", PLATFORM_SDK_VERSION);
+            *openCountPtr = -1;
+        }
     }
 
     //
@@ -873,6 +938,11 @@
         }
         cb->mappedPid = getpid();
 
+        if (isHidlGralloc) {
+            int32_t* openCountPtr = getOpenCountPtr(cb);
+            if (!*openCountPtr) *openCountPtr = 1;
+        }
+
         DEFINE_AND_VALIDATE_HOST_CONNECTION;
         if (rcEnc->getDmaVersion() > 0) {
             init_gralloc_dmaregion();
@@ -909,6 +979,19 @@
         D("Closing host ColorBuffer 0x%x\n", cb->hostHandle);
         DEFINE_AND_VALIDATE_HOST_CONNECTION;
         rcEnc->rcCloseColorBuffer(rcEnc, cb->hostHandle);
+
+        if (isHidlGralloc) {
+            // Queue up another rcCloseColorBuffer if applicable.
+            // invariant: have ashmem.
+            if (cb->ashmemSize > 0 && cb->mappedPid == getpid()) {
+                int32_t* openCountPtr = getOpenCountPtr(cb);
+                if (*openCountPtr == -1) {
+                    D("%s: revenge of the rcCloseColorBuffer!", __func__);
+                    rcEnc->rcCloseColorBuffer(rcEnc, cb->hostHandle);
+                    *openCountPtr = -2;
+                }
+            }
+        }
     }
 
     //
@@ -1019,13 +1102,7 @@
             return -EACCES;
         }
 
-        if (cb->canBePosted()) {
-            postCount = *((intptr_t *)cb->ashmemBase);
-            cpu_addr = (void *)(cb->ashmemBase + sizeof(intptr_t));
-        }
-        else {
-            cpu_addr = (void *)(cb->ashmemBase);
-        }
+        cpu_addr = (void *)(cb->ashmemBase + getAshmemColorOffset(cb));
     }
 
     if (cb->hostHandle) {
@@ -1117,13 +1194,7 @@
         // Make sure we have host connection
         DEFINE_AND_VALIDATE_HOST_CONNECTION;
 
-        void *cpu_addr;
-        if (cb->canBePosted()) {
-            cpu_addr = (void *)(cb->ashmemBase + sizeof(int));
-        }
-        else {
-            cpu_addr = (void *)(cb->ashmemBase);
-        }
+        void *cpu_addr = (void *)(cb->ashmemBase + getAshmemColorOffset(cb));
 
         char* rgb_addr = (char *)cpu_addr;
         if (cb->lockedWidth < cb->width || cb->lockedHeight < cb->height) {
@@ -1180,13 +1251,7 @@
     }
 
     uint8_t *cpu_addr = NULL;
-
-    if (cb->canBePosted()) {
-        cpu_addr = (uint8_t *)(cb->ashmemBase + sizeof(int));
-    }
-    else {
-        cpu_addr = (uint8_t *)(cb->ashmemBase);
-    }
+    cpu_addr = (uint8_t *)(cb->ashmemBase) + getAshmemColorOffset(cb);
 
     // Calculate offsets to underlying YUV data
     size_t yStride;
diff --git a/system/surfaceInterface/Android.mk b/system/surfaceInterface/Android.mk
deleted file mode 100644
index db62d41..0000000
--- a/system/surfaceInterface/Android.mk
+++ /dev/null
@@ -1,17 +0,0 @@
-ifneq (false,$(BUILD_EMULATOR_OPENGL_DRIVER))
-
-ifeq ($(TARGET_USES_HWC2), true)
-
-LOCAL_PATH := $(call my-dir)
-
-$(call emugl-begin-static-library,libsurfaceInterface)
-$(call emugl-import,libOpenglSystemCommon)
-
-LOCAL_SRC_FILES := surfaceInterface.cpp
-LOCAL_SHARED_LIBRARIES := libgui
-
-$(call emugl-end-module)
-
-endif
-
-endif # BUILD_EMULATOR_OPENGL_DRIVER != false
diff --git a/system/surfaceInterface/surfaceInterface.cpp b/system/surfaceInterface/surfaceInterface.cpp
deleted file mode 100644
index 68f9110..0000000
--- a/system/surfaceInterface/surfaceInterface.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-#include "surfaceInterface.h"
-
-#include <cutils/log.h>
-#include <gui/Surface.h>
-
-class SurfaceInterface : public android::ANativeObjectBase<
-                                    ANativeWindow,
-                                    android::Surface,
-                                    android::RefBase> {
-public:
-    static SurfaceInterface* get();
-    void setAsyncMode(ANativeWindow* anw, bool async) {
-        ALOGD("SurfaceInterface::%s: set async mode %d", __func__, async);
-        window = anw;
-        android::Surface* s = android::Surface::getSelf(window);
-        s->setAsyncMode(async);
-        window = NULL;
-    }
-    ANativeWindow* window;
-};
-
-static SurfaceInterface* sSurfaceInterface = NULL;
-
-SurfaceInterface* SurfaceInterface::get() {
-    if (!sSurfaceInterface)
-        sSurfaceInterface = new SurfaceInterface;
-    return sSurfaceInterface;
-}
-
-extern "C" void surfaceInterface_init() {
-    SurfaceInterface::get();
-}
-
-extern "C" void surfaceInterface_setAsyncModeForWindow(void* window) {
-    SurfaceInterface::get()->setAsyncMode((ANativeWindow*)window, true);
-}
diff --git a/system/surfaceInterface/surfaceInterface.h b/system/surfaceInterface/surfaceInterface.h
deleted file mode 100644
index 6890847..0000000
--- a/system/surfaceInterface/surfaceInterface.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
-* Copyright (C) 2017 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-#pragma once
-
-#if PLATFORM_SDK_VERSION >= 16
-#include <system/window.h>
-#else // PLATFORM_SDK_VERSION >= 16
-#include <private/ui/android_natives_priv.h>
-#endif // PLATFORM_SDK_VERSION >= 16
-
-extern "C" void surfaceInterface_init();
-extern "C" void surfaceInterface_setAsyncModeForWindow(void* window);