Merge "hwc2: Update layer frame rate from metadata only if it is valid"
diff --git a/.clang-format b/.clang-format
index 9082c40..26ce4fe 100644
--- a/.clang-format
+++ b/.clang-format
@@ -1,6 +1,7 @@
 ---
 Language:        Cpp
 BasedOnStyle:  Google
+Standard : C++11
 AllowShortIfStatementsOnASingleLine: false
 AllowShortLoopsOnASingleLine: false
 AllowShortFunctionsOnASingleLine: Inline
diff --git a/Android.mk b/Android.mk
index a4d5687..a9b1175 100644
--- a/Android.mk
+++ b/Android.mk
@@ -7,7 +7,7 @@
                     $(sdm-libs)/hwc2 gpu_tonemapper libdrmutils libdisplayconfig
 endif
 
-display-hals += libgralloc1
+display-hals += gralloc
 
 ifeq ($(call is-vendor-board-platform,QCOM),true)
     include $(call all-named-subdir-makefiles,$(display-hals))
diff --git a/gpu_tonemapper/TonemapFactory.cpp b/gpu_tonemapper/TonemapFactory.cpp
index 3233682..db4b8be 100644
--- a/gpu_tonemapper/TonemapFactory.cpp
+++ b/gpu_tonemapper/TonemapFactory.cpp
@@ -18,7 +18,7 @@
  */
 
 #include "TonemapFactory.h"
-#include <utils/Log.h>
+#include <log/log.h>
 #include "Tonemapper.h"
 #include "engine.h"
 
diff --git a/gpu_tonemapper/glengine.cpp b/gpu_tonemapper/glengine.cpp
index 6c94c23..35e1932 100644
--- a/gpu_tonemapper/glengine.cpp
+++ b/gpu_tonemapper/glengine.cpp
@@ -18,7 +18,7 @@
  */
 
 #include "glengine.h"
-#include <utils/Log.h>
+#include <log/log.h>
 #include "engine.h"
 
 void checkGlError(const char *, int);
diff --git a/gralloc/Android.mk b/gralloc/Android.mk
new file mode 100644
index 0000000..3d19ce1
--- /dev/null
+++ b/gralloc/Android.mk
@@ -0,0 +1,101 @@
+# Gralloc module
+LOCAL_PATH := $(call my-dir)
+include $(LOCAL_PATH)/../common.mk
+include $(CLEAR_VARS)
+
+LOCAL_MODULE                  := gralloc.$(TARGET_BOARD_PLATFORM)
+LOCAL_VENDOR_MODULE           := true
+LOCAL_MODULE_RELATIVE_PATH    := hw
+LOCAL_MODULE_TAGS             := optional
+LOCAL_C_INCLUDES              := $(common_includes)
+
+LOCAL_HEADER_LIBRARIES        := display_headers
+LOCAL_SHARED_LIBRARIES        := $(common_libs) libqdMetaData libsync libgrallocutils \
+                                  libgralloccore android.hardware.graphics.mapper@2.0
+LOCAL_CFLAGS                  := $(common_flags) -DLOG_TAG=\"qdgralloc\" -Wall -std=c++14 -Werror
+LOCAL_CFLAGS                  += -isystem  $(kernel_includes)
+LOCAL_CLANG                   := true
+LOCAL_ADDITIONAL_DEPENDENCIES := $(common_deps)
+LOCAL_SRC_FILES               := gr_device_impl.cpp
+LOCAL_COPY_HEADERS_TO         := $(common_header_export_path)
+LOCAL_COPY_HEADERS            := gr_device_impl.h gralloc_priv.h gr_priv_handle.h
+include $(BUILD_SHARED_LIBRARY)
+
+#libgrallocutils
+include $(CLEAR_VARS)
+LOCAL_MODULE                  := libgrallocutils
+LOCAL_VENDOR_MODULE           := true
+LOCAL_MODULE_TAGS             := optional
+LOCAL_C_INCLUDES              := $(common_includes) $(kernel_includes)
+LOCAL_HEADER_LIBRARIES        := display_headers
+LOCAL_SHARED_LIBRARIES        := $(common_libs) libqdMetaData libdl  \
+                                  android.hardware.graphics.mapper@2.0
+LOCAL_CFLAGS                  := $(common_flags) -DLOG_TAG=\"qdgralloc\" -Wno-sign-conversion
+LOCAL_ADDITIONAL_DEPENDENCIES := $(common_deps)
+LOCAL_SRC_FILES               := gr_utils.cpp gr_adreno_info.cpp
+include $(BUILD_SHARED_LIBRARY)
+
+#libgralloccore
+include $(CLEAR_VARS)
+LOCAL_MODULE                  := libgralloccore
+LOCAL_VENDOR_MODULE           := true
+LOCAL_MODULE_TAGS             := optional
+LOCAL_C_INCLUDES              := $(common_includes) $(kernel_includes)
+LOCAL_HEADER_LIBRARIES        := display_headers
+LOCAL_SHARED_LIBRARIES        := $(common_libs) libqdMetaData libdl libgrallocutils \
+                                  android.hardware.graphics.mapper@2.0
+LOCAL_CFLAGS                  := $(common_flags) -DLOG_TAG=\"qdgralloc\" -Wno-sign-conversion
+LOCAL_ADDITIONAL_DEPENDENCIES := $(common_deps)
+LOCAL_SRC_FILES               := gr_allocator.cpp gr_buf_mgr.cpp gr_ion_alloc.cpp
+include $(BUILD_SHARED_LIBRARY)
+
+
+qti_mapper_version := $(shell \
+    if [ -d "$(TOP)/vendor/qcom/opensource/interfaces/display/mapper/1.0" ];\
+    then echo QTI_MAPPER_1_0; fi)
+
+qti_allocator_version := $(shell \
+    if [ -d "$(TOP)/vendor/qcom/opensource/interfaces/display/allocator/1.0" ];\
+    then echo QTI_ALLOCATOR_1_0; fi)
+
+
+#mapper
+include $(CLEAR_VARS)
+LOCAL_MODULE                  := android.hardware.graphics.mapper@2.0-impl-qti-display
+LOCAL_VENDOR_MODULE           := true
+LOCAL_MODULE_RELATIVE_PATH    := hw
+LOCAL_MODULE_TAGS             := optional
+LOCAL_C_INCLUDES              := $(common_includes) $(kernel_includes)
+LOCAL_HEADER_LIBRARIES        := display_headers
+LOCAL_SHARED_LIBRARIES        := $(common_libs) \
+                                  libhidlbase \
+                                  libhidltransport \
+                                  libqdMetaData \
+                                  libgrallocutils \
+                                  libgralloccore \
+                                  libsync \
+                                  android.hardware.graphics.mapper@2.0
+LOCAL_CFLAGS                  := $(common_flags) -DLOG_TAG=\"qdgralloc\" -Wno-sign-conversion
+LOCAL_ADDITIONAL_DEPENDENCIES := $(common_deps)
+LOCAL_SRC_FILES               := QtiMapper.cpp
+include $(BUILD_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE                  := vendor.qti.hardware.display.allocator@1.0-service
+LOCAL_VENDOR_MODULE           := true
+LOCAL_MODULE_RELATIVE_PATH    := hw
+LOCAL_MODULE_TAGS             := optional
+LOCAL_HEADER_LIBRARIES        := display_headers
+LOCAL_SHARED_LIBRARIES        := $(common_libs) \
+                                 libhidlbase \
+                                 libhidltransport\
+                                 libqdMetaData \
+                                 libgrallocutils \
+                                 libgralloccore \
+                                 android.hardware.graphics.allocator@2.0
+LOCAL_CFLAGS                  := -DLOG_TAG=\"qdgralloc\" $(common_flags)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(common_deps)
+LOCAL_C_INCLUDES              := $(common_includes) $(kernel_includes)
+LOCAL_SRC_FILES               := QtiAllocator.cpp service.cpp
+LOCAL_INIT_RC                 := vendor.qti.hardware.display.allocator@1.0-service.rc
+include $(BUILD_EXECUTABLE)
diff --git a/gralloc/QtiAllocator.cpp b/gralloc/QtiAllocator.cpp
new file mode 100644
index 0000000..c4d7aef
--- /dev/null
+++ b/gralloc/QtiAllocator.cpp
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2018, The Linux Foundation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *    * Redistributions of source code must retain the above copyright
+ *      notice, this list of conditions and the following disclaimer.
+ *    * Redistributions in binary form must reproduce the above
+ *      copyright notice, this list of conditions and the following
+ *      disclaimer in the documentation and/or other materials provided
+ *      with the distribution.
+ *    * Neither the name of The Linux Foundation. nor the names of its
+ *      contributors may be used to endorse or promote products derived
+ *      from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+ * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#define DEBUG 0
+#include "QtiAllocator.h"
+
+#include <log/log.h>
+#include <vector>
+
+#include "gr_utils.h"
+
+namespace vendor {
+namespace qti {
+namespace hardware {
+namespace display {
+namespace allocator {
+namespace V1_0 {
+namespace implementation {
+
+using android::hardware::hidl_handle;
+using gralloc::BufferDescriptor;
+
+QtiAllocator::QtiAllocator() {
+  buf_mgr_ = BufferManager::GetInstance();
+}
+
+// Methods from ::android::hardware::graphics::allocator::V2_0::IAllocator follow.
+Return<void> QtiAllocator::dumpDebugInfo(dumpDebugInfo_cb hidl_cb) {
+  std::ostringstream os;
+  buf_mgr_->Dump(&os);
+  hidl_string reply;
+  reply.setToExternal(os.str().c_str(), os.str().length());
+  hidl_cb(reply);
+  return Void();
+}
+
+Return<void> QtiAllocator::allocate(const hidl_vec<uint32_t> &descriptor, uint32_t count,
+                                    allocate_cb hidl_cb) {
+  ALOGD_IF(DEBUG, "Allocating buffers count: %d", count);
+  gralloc::BufferDescriptor desc;
+
+  auto err = desc.Decode(descriptor);
+  if (err != Error::NONE) {
+    hidl_cb(err, 0, hidl_vec<hidl_handle>());
+    return Void();
+  }
+
+  std::vector<hidl_handle> buffers;
+  buffers.reserve(count);
+  for (uint32_t i = 0; i < count; i++) {
+    buffer_handle_t buffer;
+    ALOGD_IF(DEBUG, "buffer: %p", &buffer);
+    err = buf_mgr_->AllocateBuffer(desc, &buffer);
+    if (err != Error::NONE) {
+      break;
+    }
+    buffers.emplace_back(hidl_handle(buffer));
+  }
+
+  uint32_t stride = 0;
+  hidl_vec<hidl_handle> hidl_buffers;
+  if (err == Error::NONE && buffers.size() > 0) {
+    stride = static_cast<uint32_t>(PRIV_HANDLE_CONST(buffers[0].getNativeHandle())->width);
+    hidl_buffers.setToExternal(buffers.data(), buffers.size());
+  }
+  hidl_cb(err, stride, hidl_buffers);
+
+  for (const auto &b : buffers) {
+    buf_mgr_->ReleaseBuffer(PRIV_HANDLE_CONST(b.getNativeHandle()));
+  }
+
+  return Void();
+}
+
+// Methods from ::android::hidl::base::V1_0::IBase follow.
+
+IAllocator *HIDL_FETCH_IAllocator(const char * /* name */) {
+  return new QtiAllocator();
+}
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace allocator
+}  // namespace display
+}  // namespace hardware
+}  // namespace qti
+}  // namespace vendor
diff --git a/gralloc/QtiAllocator.h b/gralloc/QtiAllocator.h
new file mode 100644
index 0000000..1e683e8
--- /dev/null
+++ b/gralloc/QtiAllocator.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2018, The Linux Foundation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *    * Redistributions of source code must retain the above copyright
+ *      notice, this list of conditions and the following disclaimer.
+ *    * Redistributions in binary form must reproduce the above
+ *      copyright notice, this list of conditions and the following
+ *      disclaimer in the documentation and/or other materials provided
+ *      with the distribution.
+ *    * Neither the name of The Linux Foundation. nor the names of its
+ *      contributors may be used to endorse or promote products derived
+ *      from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+ * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __QTIALLOCATOR_H__
+#define __QTIALLOCATOR_H__
+
+#include <hidl/MQDescriptor.h>
+#include <hidl/Status.h>
+#include <android/hardware/graphics/allocator/2.0/IAllocator.h>
+
+#include "gr_buf_mgr.h"
+
+namespace vendor {
+namespace qti {
+namespace hardware {
+namespace display {
+namespace allocator {
+namespace V1_0 {
+namespace implementation {
+
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::graphics::allocator::V2_0::IAllocator;
+using ::android::hardware::graphics::mapper::V2_0::Error;
+using ::android::hardware::hidl_array;
+using ::android::hardware::hidl_memory;
+using ::android::hardware::hidl_string;
+using ::android::hardware::hidl_vec;
+using ::android::hidl::base::V1_0::DebugInfo;
+using ::android::hidl::base::V1_0::IBase;
+using ::android::sp;
+using gralloc::BufferManager;
+
+class QtiAllocator : public IAllocator {
+ public:
+  QtiAllocator();
+  // Methods from ::android::hardware::graphics::allocator::V2_0::IAllocator follow.
+  Return<void> dumpDebugInfo(dumpDebugInfo_cb _hidl_cb) override;
+  Return<void> allocate(const hidl_vec<uint32_t> &descriptor, uint32_t count,
+                        allocate_cb _hidl_cb) override;
+
+  // Methods from ::android::hidl::base::V1_0::IBase follow.
+ private:
+  BufferManager *buf_mgr_ = nullptr;
+};
+
+extern "C" IAllocator *HIDL_FETCH_IAllocator(const char *name);
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace allocator
+}  // namespace display
+}  // namespace hardware
+}  // namespace qti
+}  // namespace vendor
+
+#endif  // __QTIALLOCATOR_H__
diff --git a/gralloc/QtiMapper.cpp b/gralloc/QtiMapper.cpp
new file mode 100644
index 0000000..8de28f5
--- /dev/null
+++ b/gralloc/QtiMapper.cpp
@@ -0,0 +1,345 @@
+/*
+ * Copyright (c) 2018, The Linux Foundation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ *       copyright notice, this list of conditions and the following
+ *       disclaimer in the documentation and/or other materials provided
+ *       with the distribution.
+ *     * Neither the name of The Linux Foundation nor the names of its
+ *       contributors may be used to endorse or promote products derived
+ *       from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+ * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#define ATRACE_TAG (ATRACE_TAG_GRAPHICS | ATRACE_TAG_HAL)
+#define DEBUG 0
+#include "QtiMapper.h"
+#include <cutils/trace.h>
+#include <qdMetaData.h>
+#include <sync/sync.h>
+#include "gr_utils.h"
+
+namespace vendor {
+namespace qti {
+namespace hardware {
+namespace display {
+namespace mapper {
+namespace V1_0 {
+namespace implementation {
+
+using gralloc::BufferInfo;
+
+QtiMapper::QtiMapper() {
+  buf_mgr_ = BufferManager::GetInstance();
+  ALOGD_IF(DEBUG, "Created QtiMapper instance");
+}
+
+bool QtiMapper::ValidDescriptor(const IMapper::BufferDescriptorInfo &bd) {
+  if (bd.width == 0 || bd.height == 0 || (static_cast<int32_t>(bd.format) <= 0) ||
+      bd.layerCount != 1) {
+    return false;
+  }
+
+  return true;
+}
+
+// Methods from ::android::hardware::graphics::mapper::V2_0::IMapper follow.
+Return<void> QtiMapper::createDescriptor(const IMapper::BufferDescriptorInfo &descriptor_info,
+                                         createDescriptor_cb hidl_cb) {
+  ALOGD_IF(DEBUG,
+           "BufferDescriptorInfo: wxh: %dx%d usage: 0x%" PRIu64 " format: %d layer_count: %d",
+           descriptor_info.width, descriptor_info.height, descriptor_info.usage,
+           static_cast<uint32_t>(descriptor_info.format), descriptor_info.layerCount);
+
+  if (ValidDescriptor(descriptor_info)) {
+    auto vec = gralloc::BufferDescriptor::Encode(descriptor_info);
+    hidl_cb(Error::NONE, vec);
+  } else {
+    hidl_cb(Error::BAD_VALUE, hidl_vec<uint32_t>());
+  }
+  return Void();
+}
+
+Return<void> QtiMapper::importBuffer(const hidl_handle &raw_handle, importBuffer_cb hidl_cb) {
+  if (!raw_handle.getNativeHandle()) {
+    ALOGE("%s: Unable to import handle", __FUNCTION__);
+    hidl_cb(Error::BAD_BUFFER, nullptr);
+    return Void();
+  }
+
+  native_handle_t *buffer_handle = native_handle_clone(raw_handle.getNativeHandle());
+  if (!buffer_handle) {
+    ALOGE("%s: Unable to clone handle", __FUNCTION__);
+    hidl_cb(Error::NO_RESOURCES, nullptr);
+    return Void();
+  }
+
+  auto error = buf_mgr_->RetainBuffer(PRIV_HANDLE_CONST(buffer_handle));
+  if (error != Error::NONE) {
+    ALOGE("%s: Unable to retain handle: %p", __FUNCTION__, buffer_handle);
+    native_handle_close(buffer_handle);
+    native_handle_delete(buffer_handle);
+
+    hidl_cb(error, nullptr);
+    return Void();
+  }
+  ALOGD_IF(DEBUG, "Imported handle: %p id: %" PRIu64, buffer_handle,
+           PRIV_HANDLE_CONST(buffer_handle)->id);
+  hidl_cb(Error::NONE, buffer_handle);
+  return Void();
+}
+
+Return<Error> QtiMapper::freeBuffer(void *buffer) {
+  if (!buffer) {
+    return Error::BAD_BUFFER;
+  }
+  return buf_mgr_->ReleaseBuffer(PRIV_HANDLE_CONST(buffer));
+}
+
+bool QtiMapper::GetFenceFd(const hidl_handle &fence_handle, int *outFenceFd) {
+  auto handle = fence_handle.getNativeHandle();
+  if (handle && handle->numFds > 1) {
+    ALOGE("invalid fence handle with %d fds", handle->numFds);
+    return false;
+  }
+
+  *outFenceFd = (handle && handle->numFds == 1) ? handle->data[0] : -1;
+  return true;
+}
+
+void QtiMapper::WaitFenceFd(int fence_fd) {
+  if (fence_fd < 0) {
+    return;
+  }
+
+  const int timeout = 3000;
+  ATRACE_BEGIN("fence wait");
+  const int error = sync_wait(fence_fd, timeout);
+  ATRACE_END();
+  if (error < 0) {
+    ALOGE("QtiMapper: lock fence %d didn't signal in %u ms -  error: %s", fence_fd, timeout,
+          strerror(errno));
+  }
+}
+
+Error QtiMapper::LockBuffer(void *buffer, uint64_t usage, const hidl_handle &acquire_fence) {
+  if (!buffer) {
+    return Error::BAD_BUFFER;
+  }
+
+  int fence_fd;
+  if (!GetFenceFd(acquire_fence, &fence_fd)) {
+    return Error::BAD_VALUE;
+  }
+
+  if (fence_fd > 0) {
+    WaitFenceFd(fence_fd);
+  }
+
+  auto hnd = PRIV_HANDLE_CONST(buffer);
+
+  return buf_mgr_->LockBuffer(hnd, usage);
+}
+
+Return<void> QtiMapper::lock(void *buffer, uint64_t cpu_usage,
+                             const IMapper::Rect & /*access_region*/,
+                             const hidl_handle &acquire_fence, lock_cb hidl_cb) {
+  auto err = LockBuffer(buffer, cpu_usage, acquire_fence);
+  if (err != Error::NONE) {
+    hidl_cb(err, nullptr);
+    return Void();
+  }
+
+  auto hnd = PRIV_HANDLE_CONST(buffer);
+  auto *out_data = reinterpret_cast<void *>(hnd->base);
+  hidl_cb(Error::NONE, out_data);
+  return Void();
+}
+
+Return<void> QtiMapper::lockYCbCr(void *buffer, uint64_t cpu_usage,
+                                  const IMapper::Rect & /*access_region*/,
+                                  const hidl_handle &acquire_fence, lockYCbCr_cb hidl_cb) {
+  YCbCrLayout layout = {};
+  auto err = LockBuffer(buffer, cpu_usage, acquire_fence);
+  if (err != Error::NONE) {
+    hidl_cb(err, layout);
+    return Void();
+  }
+
+  auto hnd = PRIV_HANDLE_CONST(buffer);
+  android_ycbcr yuv_plane_info[2];
+  if (gralloc::GetYUVPlaneInfo(hnd, yuv_plane_info) != 0) {
+    hidl_cb(Error::BAD_VALUE, layout);
+  }
+  layout.y = yuv_plane_info[0].y;
+  layout.cr = yuv_plane_info[0].cr;
+  layout.cb = yuv_plane_info[0].cb;
+  layout.yStride = static_cast<uint32_t>(yuv_plane_info[0].ystride);
+  layout.cStride = static_cast<uint32_t>(yuv_plane_info[0].cstride);
+  layout.chromaStep = static_cast<uint32_t>(yuv_plane_info[0].chroma_step);
+  hidl_cb(Error::NONE, layout);
+  return Void();
+}
+
+Return<void> QtiMapper::unlock(void *buffer, unlock_cb hidl_cb) {
+  auto err = Error::BAD_BUFFER;
+  if (buffer != nullptr) {
+    err = buf_mgr_->UnlockBuffer(PRIV_HANDLE_CONST(buffer));
+  }
+  // We don't have a release fence
+  hidl_cb(err, hidl_handle(nullptr));
+  return Void();
+}
+
+#ifdef ENABLE_QTI_MAPPER_EXTENSION
+Return<void> QtiMapper::getMapSecureBufferFlag(void *buffer, getMapSecureBufferFlag_cb hidl_cb) {
+  auto err = Error::BAD_BUFFER;
+  auto hnd = static_cast<private_handle_t *>(buffer);
+  int *map_secure_buffer = 0;
+  if (buffer != nullptr && private_handle_t::validate(hnd) != 0) {
+    if (getMetaData(hnd, GET_MAP_SECURE_BUFFER, map_secure_buffer) != 0) {
+      *map_secure_buffer = 0;
+    } else {
+      err = Error::NONE;
+    }
+  }
+  hidl_cb(err, *map_secure_buffer != 0);
+  return Void();
+}
+
+Return<void> QtiMapper::getInterlacedFlag(void *buffer, getInterlacedFlag_cb hidl_cb) {
+  auto err = Error::BAD_BUFFER;
+  auto hnd = static_cast<private_handle_t *>(buffer);
+  int *interlaced_flag = nullptr;
+  if (buffer != nullptr && private_handle_t::validate(hnd) != 0) {
+    if (getMetaData(hnd, GET_PP_PARAM_INTERLACED, interlaced_flag) != 0) {
+      *interlaced_flag = 0;
+    } else {
+      err = Error::NONE;
+    }
+  }
+  hidl_cb(err, *interlaced_flag != 0);
+  return Void();
+}
+
+Return<void> QtiMapper::getCustomDimensions(void *buffer, getCustomDimensions_cb hidl_cb) {
+  auto err = Error::BAD_BUFFER;
+  auto hnd = static_cast<private_handle_t *>(buffer);
+  int stride = 0;
+  int height = 0;
+  if (buffer != nullptr && private_handle_t::validate(hnd) != 0) {
+    stride = hnd->width;
+    height = hnd->height;
+    gralloc::GetCustomDimensions(hnd, &stride, &height);
+    err = Error::NONE;
+  }
+  hidl_cb(err, stride, height);
+  return Void();
+}
+
+Return<void> QtiMapper::getRgbDataAddress(void *buffer, getRgbDataAddress_cb hidl_cb) {
+  auto err = Error::BAD_BUFFER;
+  auto hnd = static_cast<private_handle_t *>(buffer);
+  void *rgb_data = nullptr;
+  if (buffer != nullptr && private_handle_t::validate(hnd) != 0) {
+    if (gralloc::GetRgbDataAddress(hnd, &rgb_data) == 0) {
+      err = Error::NONE;
+    }
+  }
+  hidl_cb(err, rgb_data);
+  return Void();
+}
+
+Return<void> QtiMapper::calculateBufferAttributes(int32_t width, int32_t height, int32_t format,
+                                                  uint64_t usage,
+                                                  calculateBufferAttributes_cb hidl_cb) {
+  unsigned int alignedw, alignedh;
+  BufferInfo info(width, height, format, usage);
+  gralloc::GetAlignedWidthAndHeight(info, &alignedw, &alignedh);
+  bool ubwc_enabled = gralloc::IsUBwcEnabled(format, usage);
+  hidl_cb(Error::NONE, alignedw, alignedh, ubwc_enabled);
+  return Void();
+}
+
+Return<void> QtiMapper::getColorSpace(void *buffer, getColorSpace_cb hidl_cb) {
+  auto err = Error::BAD_BUFFER;
+  auto hnd = static_cast<private_handle_t *>(buffer);
+  int color_space = 0;
+  if (buffer != nullptr && private_handle_t::validate(hnd) != 0) {
+    gralloc::GetColorSpaceFromMetadata(hnd, &color_space);
+    err = Error::NONE;
+  }
+  hidl_cb(err, color_space);
+  return Void();
+}
+
+Return<void> QtiMapper::getYuvPlaneInfo(void *buffer, getYuvPlaneInfo_cb hidl_cb) {
+  auto err = Error::BAD_BUFFER;
+  auto hnd = static_cast<private_handle_t *>(buffer);
+  hidl_vec<YCbCrLayout> layout;
+  layout.resize(2);
+  android_ycbcr yuv_plane_info[2];
+  if (buffer != nullptr && private_handle_t::validate(hnd) != 0) {
+    if (gralloc::GetYUVPlaneInfo(hnd, yuv_plane_info) == 0) {
+      err = Error::NONE;
+      for (int i=0; i < 2; i++) {
+        layout[i].y = yuv_plane_info[i].y;
+        layout[i].cr = yuv_plane_info[i].cr;
+        layout[i].cb = yuv_plane_info[i].cb;
+        layout[i].yStride = static_cast<uint32_t>(yuv_plane_info[i].ystride);
+        layout[i].cStride = static_cast<uint32_t>(yuv_plane_info[i].cstride);
+        layout[i].chromaStep = static_cast<uint32_t>(yuv_plane_info[i].chroma_step);
+      }
+    }
+  }
+  hidl_cb(err, layout);
+  return Void();
+}
+
+Return<Error> QtiMapper::setSingleBufferMode(void *buffer, bool enable) {
+  auto err = Error::BAD_BUFFER;
+  auto hnd = static_cast<private_handle_t *>(buffer);
+  if (buffer != nullptr && private_handle_t::validate(hnd) != 0) {
+    if (setMetaData(hnd, SET_SINGLE_BUFFER_MODE, &enable) != 0) {
+      err = Error::UNSUPPORTED;
+    } else {
+      err = Error::NONE;
+    }
+  }
+  return err;
+}
+#endif
+
+// Methods from ::android::hidl::base::V1_0::IBase follow.
+
+// When we are in passthrough mode, this method is used
+// by hidl to obtain the SP HAL object
+IMapper *HIDL_FETCH_IMapper(const char * /* name */) {
+  ALOGD_IF(DEBUG, "Fetching IMapper from QtiMapper");
+  auto mapper = new QtiMapper();
+  return static_cast<IMapper *>(mapper);
+}
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace mapper
+}  // namespace display
+}  // namespace hardware
+}  // namespace qti
+}  // namespace vendor
diff --git a/gralloc/QtiMapper.h b/gralloc/QtiMapper.h
new file mode 100644
index 0000000..218f074
--- /dev/null
+++ b/gralloc/QtiMapper.h
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2018, The Linux Foundation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ *       copyright notice, this list of conditions and the following
+ *       disclaimer in the documentation and/or other materials provided
+ *       with the distribution.
+ *     * Neither the name of The Linux Foundation nor the names of its
+ *       contributors may be used to endorse or promote products derived
+ *       from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+ * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __QTIMAPPER_H__
+#define __QTIMAPPER_H__
+
+#include <hidl/MQDescriptor.h>
+#include <hidl/Status.h>
+
+#include "gr_buf_mgr.h"
+namespace vendor {
+namespace qti {
+namespace hardware {
+namespace display {
+namespace mapper {
+namespace V1_0 {
+namespace implementation {
+
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::graphics::mapper::V2_0::Error;
+using ::android::hardware::graphics::mapper::V2_0::IMapper;
+using ::android::hardware::graphics::mapper::V2_0::YCbCrLayout;
+using ::android::hardware::hidl_array;
+using ::android::hardware::hidl_handle;
+using ::android::hardware::hidl_memory;
+using ::android::hardware::hidl_string;
+using ::android::hardware::hidl_vec;
+using ::android::hidl::base::V1_0::DebugInfo;
+using ::android::hidl::base::V1_0::IBase;
+using ::android::sp;
+using gralloc::BufferManager;
+
+class QtiMapper : public IMapper {
+ public:
+  QtiMapper();
+  // Methods from ::android::hardware::graphics::mapper::V2_0::IMapper follow.
+  Return<void> createDescriptor(const IMapper::BufferDescriptorInfo &descriptor_info,
+                                createDescriptor_cb hidl_cb) override;
+  Return<void> importBuffer(const hidl_handle &raw_handle, importBuffer_cb hidl_cb) override;
+  Return<Error> freeBuffer(void *buffer) override;
+  Return<void> lock(void *buffer, uint64_t cpu_usage, const IMapper::Rect &access_region,
+                    const hidl_handle &acquire_fence, lock_cb hidl_cb) override;
+  Return<void> lockYCbCr(void *buffer, uint64_t cpu_usage, const IMapper::Rect &access_region,
+                         const hidl_handle &acquire_fence, lockYCbCr_cb hidl_cb) override;
+  Return<void> unlock(void *buffer, unlock_cb hidl_cb) override;
+
+#ifdef ENABLE_QTI_MAPPER_EXTENSION
+  Return<void> getMapSecureBufferFlag(void *buffer, getMapSecureBufferFlag_cb _hidl_cb) override;
+  Return<void> getInterlacedFlag(void *buffer, getInterlacedFlag_cb _hidl_cb) override;
+  Return<void> getCustomDimensions(void *buffer, getCustomDimensions_cb _hidl_cb) override;
+  Return<void> getRgbDataAddress(void *buffer, getRgbDataAddress_cb _hidl_cb) override;
+  Return<void> calculateBufferAttributes(int32_t width, int32_t height, int32_t format,
+                                         uint64_t usage,
+                                         calculateBufferAttributes_cb _hidl_cb) override;
+  Return<void> getColorSpace(void *buffer, getColorSpace_cb _hidl_cb) override;
+  Return<void> getYuvPlaneInfo(void *buffer, getYuvPlaneInfo_cb _hidl_cb) override;
+  Return<Error> setSingleBufferMode(void *buffer, bool enable) override;
+#endif
+
+ private:
+  BufferManager *buf_mgr_ = nullptr;
+  bool ValidDescriptor(const IMapper::BufferDescriptorInfo &bd);
+  bool GetFenceFd(const hidl_handle &fence_handle, int *outFenceFd);
+  void WaitFenceFd(int fence_fd);
+  Error LockBuffer(void *buffer, uint64_t usage, const hidl_handle &acquire_fence);
+};
+
+extern "C" IMapper *HIDL_FETCH_IMapper(const char *name);
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace mapper
+}  // namespace display
+}  // namespace hardware
+}  // namespace qti
+}  // namespace vendor
+
+#endif  // __QTIMAPPER_H__
diff --git a/libgralloc1/gr_adreno_info.cpp b/gralloc/gr_adreno_info.cpp
similarity index 93%
rename from libgralloc1/gr_adreno_info.cpp
rename to gralloc/gr_adreno_info.cpp
index 8d83627..ca77b3b 100644
--- a/libgralloc1/gr_adreno_info.cpp
+++ b/gralloc/gr_adreno_info.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2018, The Linux Foundation. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -27,19 +27,19 @@
  * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include <cutils/log.h>
+#include <log/log.h>
 #include <cutils/properties.h>
 #include <dlfcn.h>
 #include <mutex>
 
-#include "gralloc_priv.h"
 #include "gr_adreno_info.h"
 #include "gr_utils.h"
+#include "gralloc_priv.h"
 
 using std::lock_guard;
 using std::mutex;
 
-namespace gralloc1 {
+namespace gralloc {
 
 AdrenoMemInfo *AdrenoMemInfo::s_instance = nullptr;
 
@@ -130,9 +130,9 @@
     // num_samples is 1 always. We may  have to add uitility function to
     // find out these if there is a need to call this API for YUV formats.
     LINK_adreno_compute_fmt_aligned_width_and_height(
-        width, height, 0/*plane_id*/, GetGpuPixelFormat(format), 1/*num_samples*/,
-        tile_enabled, raster_mode, padding_threshold,
-        reinterpret_cast<int *>(aligned_w), reinterpret_cast<int *>(aligned_h));
+        width, height, 0 /*plane_id*/, GetGpuPixelFormat(format), 1 /*num_samples*/, tile_enabled,
+        raster_mode, padding_threshold, reinterpret_cast<int *>(aligned_w),
+        reinterpret_cast<int *>(aligned_h));
   } else if (LINK_adreno_compute_aligned_width_and_height) {
     LINK_adreno_compute_aligned_width_and_height(
         width, height, bpp, tile_enabled, raster_mode, padding_threshold,
@@ -208,13 +208,13 @@
     case HAL_PIXEL_FORMAT_YCbCr_420_P010_VENUS:
       return ADRENO_PIXELFORMAT_P010;
     case HAL_PIXEL_FORMAT_RGBA_1010102:
-       return ADRENO_PIXELFORMAT_R10G10B10A2_UNORM;
+      return ADRENO_PIXELFORMAT_R10G10B10A2_UNORM;
     case HAL_PIXEL_FORMAT_RGBX_1010102:
-       return ADRENO_PIXELFORMAT_R10G10B10X2_UNORM;
+      return ADRENO_PIXELFORMAT_R10G10B10X2_UNORM;
     case HAL_PIXEL_FORMAT_ABGR_2101010:
-       return ADRENO_PIXELFORMAT_A2B10G10R10_UNORM;
+      return ADRENO_PIXELFORMAT_A2B10G10R10_UNORM;
     case HAL_PIXEL_FORMAT_RGBA_FP16:
-       return ADRENO_PIXELFORMAT_R16G16B16A16_FLOAT;
+      return ADRENO_PIXELFORMAT_R16G16B16A16_FLOAT;
     default:
       ALOGE("%s: No map for format: 0x%x", __FUNCTION__, hal_format);
       break;
@@ -223,4 +223,4 @@
   return ADRENO_PIXELFORMAT_UNKNOWN;
 }
 
-}  // namespace gralloc1
+}  // namespace gralloc
diff --git a/libgralloc1/gr_adreno_info.h b/gralloc/gr_adreno_info.h
similarity index 90%
rename from libgralloc1/gr_adreno_info.h
rename to gralloc/gr_adreno_info.h
index 83966ae..a454d15 100644
--- a/libgralloc1/gr_adreno_info.h
+++ b/gralloc/gr_adreno_info.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2018, The Linux Foundation. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -32,7 +32,7 @@
 
 #include <media/msm_media_info.h>
 
-namespace gralloc1 {
+namespace gralloc {
 
 // Adreno Pixel Formats
 typedef enum {
@@ -57,13 +57,13 @@
   ADRENO_PIXELFORMAT_R8G8B8X8_SRGB = 520,  //  GL_SRGB8
   ADRENO_PIXELFORMAT_R8G8B8_SRGB = 521,    //  GL_SRGB8
   ADRENO_PIXELFORMAT_A2B10G10R10_UNORM = 532,
-                                          // Vertex, Normalized GL_UNSIGNED_INT_10_10_10_2_OES
+  // Vertex, Normalized GL_UNSIGNED_INT_10_10_10_2_OES
   ADRENO_PIXELFORMAT_R10G10B10X2_UNORM = 537,
-                                          // Vertex, Normalized GL_UNSIGNED_INT_10_10_10_2_OES
-  ADRENO_PIXELFORMAT_R5G6B5 = 610,         //  RGBA version of B5G6R5
-  ADRENO_PIXELFORMAT_R5G5B5A1 = 611,       //  RGBA version of B5G5R5A1
-  ADRENO_PIXELFORMAT_R4G4B4A4 = 612,       //  RGBA version of B4G4R4A4
-  ADRENO_PIXELFORMAT_UYVY = 614,           //  YUV 4:2:2 packed progressive (1 plane)
+  // Vertex, Normalized GL_UNSIGNED_INT_10_10_10_2_OES
+  ADRENO_PIXELFORMAT_R5G6B5 = 610,    //  RGBA version of B5G6R5
+  ADRENO_PIXELFORMAT_R5G5B5A1 = 611,  //  RGBA version of B5G5R5A1
+  ADRENO_PIXELFORMAT_R4G4B4A4 = 612,  //  RGBA version of B4G4R4A4
+  ADRENO_PIXELFORMAT_UYVY = 614,      //  YUV 4:2:2 packed progressive (1 plane)
   ADRENO_PIXELFORMAT_NV21 = 619,
   ADRENO_PIXELFORMAT_Y8U8V8A8 = 620,  // YUV 4:4:4 packed (1 plane)
   ADRENO_PIXELFORMAT_Y8 = 625,        //  Single 8-bit luma only channel YUV format
@@ -149,6 +149,6 @@
   static AdrenoMemInfo *s_instance;
 };
 
-}  // namespace gralloc1
+}  // namespace gralloc
 
 #endif  // __GR_ADRENO_INFO_H__
diff --git a/libgralloc1/gr_allocator.cpp b/gralloc/gr_allocator.cpp
similarity index 70%
rename from libgralloc1/gr_allocator.cpp
rename to gralloc/gr_allocator.cpp
index 066ac34..34a5c03 100644
--- a/libgralloc1/gr_allocator.cpp
+++ b/gralloc/gr_allocator.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2018, The Linux Foundation. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -27,12 +27,12 @@
  * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include <cutils/log.h>
+#include <log/log.h>
 #include <algorithm>
 #include <vector>
 
-#include "gr_utils.h"
 #include "gr_allocator.h"
+#include "gr_utils.h"
 #include "gralloc_priv.h"
 
 #include "qd_utils.h"
@@ -65,18 +65,17 @@
 #define ION_SC_PREVIEW_FLAGS ION_SECURE
 #endif
 
-using std::vector;
 using std::shared_ptr;
+using std::vector;
 
-namespace gralloc1 {
+namespace gralloc {
 
 static BufferInfo GetBufferInfo(const BufferDescriptor &descriptor) {
   return BufferInfo(descriptor.GetWidth(), descriptor.GetHeight(), descriptor.GetFormat(),
-                    descriptor.GetProducerUsage(), descriptor.GetConsumerUsage());
+                    descriptor.GetUsage());
 }
 
-Allocator::Allocator() : ion_allocator_(NULL) {
-}
+Allocator::Allocator() : ion_allocator_(nullptr) {}
 
 bool Allocator::Init() {
   ion_allocator_ = new IonAlloc();
@@ -93,14 +92,12 @@
   }
 }
 
-int Allocator::AllocateMem(AllocData *alloc_data, gralloc1_producer_usage_t prod_usage,
-                           gralloc1_consumer_usage_t cons_usage) {
+int Allocator::AllocateMem(AllocData *alloc_data, uint64_t usage) {
   int ret;
-  alloc_data->uncached = UseUncached(prod_usage, cons_usage);
+  alloc_data->uncached = UseUncached(usage);
 
   // After this point we should have the right heap set, there is no fallback
-  GetIonHeapInfo(prod_usage, cons_usage, &alloc_data->heap_id, &alloc_data->alloc_type,
-                 &alloc_data->flags);
+  GetIonHeapInfo(usage, &alloc_data->heap_id, &alloc_data->alloc_type, &alloc_data->flags);
 
   ret = ion_allocator_->AllocBuffer(alloc_data);
   if (ret >= 0) {
@@ -128,8 +125,7 @@
   return -EINVAL;
 }
 
-int Allocator::FreeBuffer(void *base, unsigned int size, unsigned int offset, int fd,
-                          int handle) {
+int Allocator::FreeBuffer(void *base, unsigned int size, unsigned int offset, int fd, int handle) {
   if (ion_allocator_) {
     return ion_allocator_->FreeBuffer(base, size, offset, fd, handle);
   }
@@ -146,7 +142,7 @@
 }
 
 bool Allocator::CheckForBufferSharing(uint32_t num_descriptors,
-                                      const vector<shared_ptr<BufferDescriptor>>& descriptors,
+                                      const vector<shared_ptr<BufferDescriptor>> &descriptors,
                                       ssize_t *max_index) {
   unsigned int cur_heap_id = 0, prev_heap_id = 0;
   unsigned int cur_alloc_type = 0, prev_alloc_type = 0;
@@ -158,10 +154,8 @@
   *max_index = -1;
   for (uint32_t i = 0; i < num_descriptors; i++) {
     // Check Cached vs non-cached and all the ION flags
-    cur_uncached = UseUncached(descriptors[i]->GetProducerUsage(),
-                               descriptors[i]->GetConsumerUsage());
-    GetIonHeapInfo(descriptors[i]->GetProducerUsage(), descriptors[i]->GetConsumerUsage(),
-                   &cur_heap_id, &cur_alloc_type, &cur_ion_flags);
+    cur_uncached = UseUncached(descriptors[i]->GetUsage());
+    GetIonHeapInfo(descriptors[i]->GetUsage(), &cur_heap_id, &cur_alloc_type, &cur_ion_flags);
 
     if (i > 0 && (cur_heap_id != prev_heap_id || cur_alloc_type != prev_alloc_type ||
                   cur_ion_flags != prev_ion_flags)) {
@@ -185,43 +179,42 @@
   return true;
 }
 
-int Allocator::GetImplDefinedFormat(gralloc1_producer_usage_t prod_usage,
-                                    gralloc1_consumer_usage_t cons_usage, int format) {
+int Allocator::GetImplDefinedFormat(uint64_t usage, int format) {
   int gr_format = format;
 
   // If input format is HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED then based on
   // the usage bits, gralloc assigns a format.
   if (format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED ||
       format == HAL_PIXEL_FORMAT_YCbCr_420_888) {
-    if (prod_usage & GRALLOC1_PRODUCER_USAGE_PRIVATE_ALLOC_UBWC) {
+    if (usage & GRALLOC_USAGE_PRIVATE_ALLOC_UBWC) {
       // Use of 10BIT_TP and 10BIT bits is supposed to be mutually exclusive.
       // Each bit maps to only one format. Here we will check one of the bits
       // and ignore the other.
-      if (prod_usage & GRALLOC1_PRODUCER_USAGE_PRIVATE_10BIT_TP) {
+      if (usage & GRALLOC_USAGE_PRIVATE_10BIT_TP) {
         gr_format = HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC;
-      } else if (prod_usage & GRALLOC1_PRODUCER_USAGE_PRIVATE_10BIT) {
+      } else if (usage & GRALLOC_USAGE_PRIVATE_10BIT) {
         gr_format = HAL_PIXEL_FORMAT_YCbCr_420_P010_UBWC;
       } else {
         gr_format = HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC;
       }
-    } else if (prod_usage & GRALLOC1_PRODUCER_USAGE_PRIVATE_10BIT) {
+    } else if (usage & GRALLOC_USAGE_PRIVATE_10BIT) {
       gr_format = HAL_PIXEL_FORMAT_YCbCr_420_P010_VENUS;
-    } else if (cons_usage & GRALLOC1_CONSUMER_USAGE_VIDEO_ENCODER) {
+    } else if (usage & BufferUsage::VIDEO_ENCODER) {
       gr_format = HAL_PIXEL_FORMAT_NV12_ENCODEABLE;  // NV12
-    } else if (cons_usage & GRALLOC1_CONSUMER_USAGE_CAMERA) {
-      if (prod_usage & GRALLOC1_PRODUCER_USAGE_CAMERA) {
+    } else if (usage & BufferUsage::CAMERA_INPUT) {
+      if (usage & BufferUsage::CAMERA_OUTPUT) {
         // Assumed ZSL if both producer and consumer camera flags set
         gr_format = HAL_PIXEL_FORMAT_NV21_ZSL;  // NV21
       } else {
         gr_format = HAL_PIXEL_FORMAT_YCrCb_420_SP;  // NV21
       }
-    } else if (prod_usage & GRALLOC1_PRODUCER_USAGE_CAMERA) {
+    } else if (usage & BufferUsage::CAMERA_OUTPUT) {
       if (format == HAL_PIXEL_FORMAT_YCbCr_420_888) {
         gr_format = HAL_PIXEL_FORMAT_NV21_ZSL;  // NV21
       } else {
         gr_format = HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS;  // NV12 preview
       }
-    } else if (cons_usage & GRALLOC1_CONSUMER_USAGE_HWCOMPOSER) {
+    } else if (usage & BufferUsage::COMPOSER_OVERLAY) {
       // XXX: If we still haven't set a format, default to RGBA8888
       gr_format = HAL_PIXEL_FORMAT_RGBA_8888;
     } else if (format == HAL_PIXEL_FORMAT_YCbCr_420_888) {
@@ -237,50 +230,44 @@
 /* The default policy is to return cached buffers unless the client explicity
  * sets the PRIVATE_UNCACHED flag or indicates that the buffer will be rarely
  * read or written in software. */
-bool Allocator::UseUncached(gralloc1_producer_usage_t prod_usage,
-                            gralloc1_consumer_usage_t cons_usage) {
-  if ((prod_usage & GRALLOC1_PRODUCER_USAGE_PRIVATE_UNCACHED) ||
-      (prod_usage & GRALLOC1_PRODUCER_USAGE_PROTECTED)) {
+bool Allocator::UseUncached(uint64_t usage) {
+  if ((usage & GRALLOC_USAGE_PRIVATE_UNCACHED) || (usage & BufferUsage::PROTECTED)) {
     return true;
   }
 
   // CPU read rarely
-  if ((prod_usage & GRALLOC1_PRODUCER_USAGE_CPU_READ) &&
-      !(prod_usage & GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN)) {
+  if ((usage & BufferUsage::CPU_READ_RARELY) && !(usage & BufferUsage::CPU_READ_OFTEN)) {
     return true;
   }
 
   // CPU  write rarely
-  if ((prod_usage & GRALLOC1_PRODUCER_USAGE_CPU_WRITE) &&
-      !(prod_usage & GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN)) {
+  if ((usage & BufferUsage::CPU_WRITE_RARELY) && !(usage & BufferUsage::CPU_WRITE_OFTEN)) {
     return true;
   }
 
-  if ((prod_usage & GRALLOC1_PRODUCER_USAGE_SENSOR_DIRECT_DATA) ||
-      (cons_usage & GRALLOC1_CONSUMER_USAGE_GPU_DATA_BUFFER)) {
+  if ((usage & BufferUsage::SENSOR_DIRECT_DATA) || (usage & BufferUsage::GPU_DATA_BUFFER)) {
     return true;
   }
 
   return false;
 }
 
-void Allocator::GetIonHeapInfo(gralloc1_producer_usage_t prod_usage,
-                               gralloc1_consumer_usage_t cons_usage, unsigned int *ion_heap_id,
-                               unsigned int *alloc_type, unsigned int *ion_flags) {
+void Allocator::GetIonHeapInfo(uint64_t usage, unsigned int *ion_heap_id, unsigned int *alloc_type,
+                               unsigned int *ion_flags) {
   unsigned int heap_id = 0;
   unsigned int type = 0;
   uint32_t flags = 0;
-  if (prod_usage & GRALLOC1_PRODUCER_USAGE_PROTECTED) {
-    if (cons_usage & GRALLOC1_CONSUMER_USAGE_PRIVATE_SECURE_DISPLAY) {
+  if (usage & GRALLOC_USAGE_PROTECTED) {
+    if (usage & GRALLOC_USAGE_PRIVATE_SECURE_DISPLAY) {
       heap_id = ION_HEAP(SD_HEAP_ID);
       /*
        * There is currently no flag in ION for Secure Display
        * VM. Please add it to the define once available.
        */
       flags |= UINT(ION_SD_FLAGS);
-    } else if (prod_usage & GRALLOC1_PRODUCER_USAGE_CAMERA) {
+    } else if (usage & BufferUsage::CAMERA_OUTPUT) {
       heap_id = ION_HEAP(SD_HEAP_ID);
-      if (cons_usage & GRALLOC1_CONSUMER_USAGE_HWCOMPOSER) {
+      if (usage & BufferUsage::COMPOSER_OVERLAY) {
         flags |= UINT(ION_SC_PREVIEW_FLAGS);
       } else {
         flags |= UINT(ION_SC_FLAGS);
@@ -289,15 +276,9 @@
       heap_id = ION_HEAP(CP_HEAP_ID);
       flags |= UINT(ION_CP_FLAGS);
     }
-  } else if (prod_usage & GRALLOC1_PRODUCER_USAGE_PRIVATE_MM_HEAP) {
-    // MM Heap is exclusively a secure heap.
-    // If it is used for non secure cases, fallback to IOMMU heap
-    ALOGW("MM_HEAP cannot be used as an insecure heap. Using system heap instead!!");
-    heap_id |= ION_HEAP(ION_SYSTEM_HEAP_ID);
   }
 
-  if (prod_usage & GRALLOC1_PRODUCER_USAGE_PRIVATE_ADSP_HEAP ||
-      prod_usage & GRALLOC1_PRODUCER_USAGE_SENSOR_DIRECT_DATA) {
+  if (usage & BufferUsage::SENSOR_DIRECT_DATA) {
     heap_id |= ION_HEAP(ION_ADSP_HEAP_ID);
   }
 
@@ -316,4 +297,4 @@
 
   return;
 }
-}  // namespace gralloc1
+}  // namespace gralloc
diff --git a/libgralloc1/gr_allocator.h b/gralloc/gr_allocator.h
similarity index 77%
rename from libgralloc1/gr_allocator.h
rename to gralloc/gr_allocator.h
index d57f50e..fd316ef 100644
--- a/libgralloc1/gr_allocator.h
+++ b/gralloc/gr_allocator.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2018, The Linux Foundation. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -38,11 +38,11 @@
 
 #include <vector>
 
-#include "gralloc_priv.h"
 #include "gr_buf_descriptor.h"
 #include "gr_ion_alloc.h"
+#include "gralloc_priv.h"
 
-namespace gralloc1 {
+namespace gralloc {
 
 class Allocator {
  public:
@@ -53,23 +53,21 @@
   int ImportBuffer(int fd);
   int FreeBuffer(void *base, unsigned int size, unsigned int offset, int fd, int handle);
   int CleanBuffer(void *base, unsigned int size, unsigned int offset, int handle, int op);
-  int AllocateMem(AllocData *data, gralloc1_producer_usage_t prod_usage,
-                  gralloc1_consumer_usage_t cons_usage);
+  int AllocateMem(AllocData *data, uint64_t usage);
   // @return : index of the descriptor with maximum buffer size req
   bool CheckForBufferSharing(uint32_t num_descriptors,
-                             const std::vector<std::shared_ptr<BufferDescriptor>>& descriptors,
+                             const std::vector<std::shared_ptr<BufferDescriptor>> &descriptors,
                              ssize_t *max_index);
-  int GetImplDefinedFormat(gralloc1_producer_usage_t prod_usage,
-                           gralloc1_consumer_usage_t cons_usage, int format);
-  bool UseUncached(gralloc1_producer_usage_t prod_usage, gralloc1_consumer_usage_t cons_usage);
+  int GetImplDefinedFormat(uint64_t usage, int format);
+  bool UseUncached(uint64_t usage);
 
  private:
-  void GetIonHeapInfo(gralloc1_producer_usage_t prod_usage, gralloc1_consumer_usage_t cons_usage,
-                      unsigned int *ion_heap_id, unsigned int *alloc_type, unsigned int *ion_flags);
+  void GetIonHeapInfo(uint64_t usage, unsigned int *ion_heap_id, unsigned int *alloc_type,
+                      unsigned int *ion_flags);
 
   IonAlloc *ion_allocator_ = NULL;
 };
 
-}  // namespace gralloc1
+}  // namespace gralloc
 
 #endif  // __GR_ALLOCATOR_H__
diff --git a/gralloc/gr_buf_descriptor.h b/gralloc/gr_buf_descriptor.h
new file mode 100644
index 0000000..932db33
--- /dev/null
+++ b/gralloc/gr_buf_descriptor.h
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2016-2018, The Linux Foundation. All rights reserved.
+
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *   * Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *   * Redistributions in binary form must reproduce the above
+ *     copyright notice, this list of conditions and the following
+ *     disclaimer in the documentation and/or other materials provided
+ *     with the distribution.
+ *   * Neither the name of The Linux Foundation nor the names of its
+ *     contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+ * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __GR_BUF_DESCRIPTOR_H__
+#define __GR_BUF_DESCRIPTOR_H__
+
+#include <android/hardware/graphics/mapper/2.0/IMapper.h>
+#include <atomic>
+
+namespace gralloc {
+using android::hardware::graphics::mapper::V2_0::Error;
+using android::hardware::graphics::mapper::V2_0::IMapper;
+using android::hardware::hidl_vec;
+
+const uint32_t kBufferDescriptorSize = 7;
+const uint32_t kMagicVersion = 0x76312E30;  // v1.0
+
+class BufferDescriptor {
+ public:
+  BufferDescriptor() {}
+  explicit BufferDescriptor(uint64_t id) : id_(id) {}
+
+  static hidl_vec<uint32_t> Encode(const IMapper::BufferDescriptorInfo &bd_info) {
+    hidl_vec<uint32_t> out;
+    out.resize(kBufferDescriptorSize);
+    out[0] = kMagicVersion;
+    out[1] = bd_info.width;
+    out[2] = bd_info.height;
+    out[3] = bd_info.layerCount;
+    out[4] = static_cast<uint32_t>(bd_info.format);
+    out[5] = static_cast<uint32_t>(bd_info.usage);
+    out[6] = static_cast<uint32_t>(bd_info.usage >> 32);
+    return out;
+  }
+
+  Error Decode(const hidl_vec<uint32_t> &in) {
+    if (in.size() != kBufferDescriptorSize || in[0] != kMagicVersion) {
+      return Error::BAD_DESCRIPTOR;
+    }
+    width_ = static_cast<int32_t>(in[1]);
+    height_ = static_cast<int32_t>(in[2]);
+    layer_count_ = in[3];
+    format_ = static_cast<int32_t>(in[4]);
+    usage_ = static_cast<uint64_t>(in[6]) << 32 | in[5];
+    return Error::NONE;
+  }
+
+  void SetUsage(uint64_t usage) { usage_ |= usage; }
+
+  void SetDimensions(int w, int h) {
+    width_ = w;
+    height_ = h;
+  }
+
+  void SetColorFormat(int format) { format_ = format; }
+
+  void SetLayerCount(uint32_t layer_count) { layer_count_ = layer_count; }
+
+  uint64_t GetUsage() const { return usage_; }
+
+  int GetWidth() const { return width_; }
+
+  int GetHeight() const { return height_; }
+
+  int GetFormat() const { return format_; }
+
+  uint32_t GetLayerCount() const { return layer_count_; }
+
+  uint64_t GetId() const { return id_; }
+
+ private:
+  int width_ = -1;
+  int height_ = -1;
+  int format_ = -1;
+  uint32_t layer_count_ = 1;
+  uint64_t usage_ = 0;
+  const uint64_t id_ = 0;
+};
+};      // namespace gralloc
+#endif  // __GR_BUF_DESCRIPTOR_H__
diff --git a/gralloc/gr_buf_mgr.cpp b/gralloc/gr_buf_mgr.cpp
new file mode 100644
index 0000000..70fb483
--- /dev/null
+++ b/gralloc/gr_buf_mgr.cpp
@@ -0,0 +1,407 @@
+/*
+ * Copyright (c) 2011-2018 The Linux Foundation. All rights reserved.
+ * Not a Contribution
+ *
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define DEBUG 0
+
+#include <iomanip>
+#include <sstream>
+#include <utility>
+#include <vector>
+
+#include "gr_buf_descriptor.h"
+#include "gr_buf_mgr.h"
+#include "gr_priv_handle.h"
+#include "gr_utils.h"
+#include "qdMetaData.h"
+#include "qd_utils.h"
+
+namespace gralloc {
+
+static BufferInfo GetBufferInfo(const BufferDescriptor &descriptor) {
+  return BufferInfo(descriptor.GetWidth(), descriptor.GetHeight(), descriptor.GetFormat(),
+                    descriptor.GetUsage());
+}
+
+BufferManager::BufferManager() : next_id_(0) {
+  char property[PROPERTY_VALUE_MAX];
+
+  // Map framebuffer memory
+  if ((property_get("debug.gralloc.map_fb_memory", property, NULL) > 0) &&
+      (!strncmp(property, "1", PROPERTY_VALUE_MAX) ||
+       (!strncasecmp(property, "true", PROPERTY_VALUE_MAX)))) {
+    map_fb_mem_ = true;
+  }
+
+  handles_map_.clear();
+  allocator_ = new Allocator();
+  allocator_->Init();
+}
+
+BufferManager *BufferManager::GetInstance() {
+  static BufferManager *instance = new BufferManager();
+  return instance;
+}
+
+BufferManager::~BufferManager() {
+  if (allocator_) {
+    delete allocator_;
+  }
+}
+
+Error BufferManager::FreeBuffer(std::shared_ptr<Buffer> buf) {
+  auto hnd = buf->handle;
+  ALOGD_IF(DEBUG, "FreeBuffer handle:%p", hnd);
+
+  if (private_handle_t::validate(hnd) != 0) {
+    ALOGE("FreeBuffer: Invalid handle: %p", hnd);
+    return Error::BAD_BUFFER;
+  }
+
+  if (allocator_->FreeBuffer(reinterpret_cast<void *>(hnd->base), hnd->size, hnd->offset, hnd->fd,
+                             buf->ion_handle_main) != 0) {
+    return Error::BAD_BUFFER;
+  }
+
+  unsigned int meta_size = ALIGN((unsigned int)sizeof(MetaData_t), PAGE_SIZE);
+  if (allocator_->FreeBuffer(reinterpret_cast<void *>(hnd->base_metadata), meta_size,
+                             hnd->offset_metadata, hnd->fd_metadata, buf->ion_handle_meta) != 0) {
+    return Error::BAD_BUFFER;
+  }
+
+  private_handle_t *handle = const_cast<private_handle_t *>(hnd);
+  handle->fd = -1;
+  handle->fd_metadata = -1;
+  if (!(handle->flags & private_handle_t::PRIV_FLAGS_CLIENT_ALLOCATED)) {
+    delete handle;
+  }
+  return Error::NONE;
+}
+
+void BufferManager::RegisterHandleLocked(const private_handle_t *hnd, int ion_handle,
+                                         int ion_handle_meta) {
+  auto buffer = std::make_shared<Buffer>(hnd, ion_handle, ion_handle_meta);
+  handles_map_.emplace(std::make_pair(hnd, buffer));
+}
+
+Error BufferManager::ImportHandleLocked(private_handle_t *hnd) {
+  ALOGD_IF(DEBUG, "Importing handle:%p id: %" PRIu64, hnd, hnd->id);
+  int ion_handle = allocator_->ImportBuffer(hnd->fd);
+  if (ion_handle < 0) {
+    ALOGE("Failed to import ion buffer: hnd: %p, fd:%d, id:%" PRIu64, hnd, hnd->fd, hnd->id);
+    return Error::BAD_BUFFER;
+  }
+  int ion_handle_meta = allocator_->ImportBuffer(hnd->fd_metadata);
+  if (ion_handle_meta < 0) {
+    ALOGE("Failed to import ion metadata buffer: hnd: %p, fd:%d, id:%" PRIu64, hnd, hnd->fd,
+          hnd->id);
+    return Error::BAD_BUFFER;
+  }
+  // Set base pointers to NULL since the data here was received over binder
+  hnd->base = 0;
+  hnd->base_metadata = 0;
+  RegisterHandleLocked(hnd, ion_handle, ion_handle_meta);
+  return Error::NONE;
+}
+
+std::shared_ptr<BufferManager::Buffer> BufferManager::GetBufferFromHandleLocked(
+    const private_handle_t *hnd) {
+  auto it = handles_map_.find(hnd);
+  if (it != handles_map_.end()) {
+    return it->second;
+  } else {
+    return nullptr;
+  }
+}
+
+Error BufferManager::MapBuffer(private_handle_t const *handle) {
+  private_handle_t *hnd = const_cast<private_handle_t *>(handle);
+  ALOGD_IF(DEBUG, "Map buffer handle:%p id: %" PRIu64, hnd, hnd->id);
+
+  hnd->base = 0;
+  if (allocator_->MapBuffer(reinterpret_cast<void **>(&hnd->base), hnd->size, hnd->offset,
+                            hnd->fd) != 0) {
+    return Error::BAD_BUFFER;
+  }
+  return Error::NONE;
+}
+
+Error BufferManager::RetainBuffer(private_handle_t const *hnd) {
+  ALOGD_IF(DEBUG, "Retain buffer handle:%p id: %" PRIu64, hnd, hnd->id);
+  auto err = Error::NONE;
+  std::lock_guard<std::mutex> lock(buffer_lock_);
+  auto buf = GetBufferFromHandleLocked(hnd);
+  if (buf != nullptr) {
+    buf->IncRef();
+  } else {
+    private_handle_t *handle = const_cast<private_handle_t *>(hnd);
+    err = ImportHandleLocked(handle);
+  }
+  return err;
+}
+
+Error BufferManager::ReleaseBuffer(private_handle_t const *hnd) {
+  ALOGD_IF(DEBUG, "Release buffer handle:%p", hnd);
+  std::lock_guard<std::mutex> lock(buffer_lock_);
+  auto buf = GetBufferFromHandleLocked(hnd);
+  if (buf == nullptr) {
+    ALOGE("Could not find handle: %p id: %" PRIu64, hnd, hnd->id);
+    return Error::BAD_BUFFER;
+  } else {
+    if (buf->DecRef()) {
+      handles_map_.erase(hnd);
+      // Unmap, close ion handle and close fd
+      FreeBuffer(buf);
+    }
+  }
+  return Error::NONE;
+}
+
+Error BufferManager::LockBuffer(const private_handle_t *hnd, uint64_t usage) {
+  std::lock_guard<std::mutex> lock(buffer_lock_);
+  auto err = Error::NONE;
+  ALOGD_IF(DEBUG, "LockBuffer buffer handle:%p id: %" PRIu64, hnd, hnd->id);
+
+  // If buffer is not meant for CPU return err
+  if (!CpuCanAccess(usage)) {
+    return Error::BAD_VALUE;
+  }
+
+  auto buf = GetBufferFromHandleLocked(hnd);
+  if (buf == nullptr) {
+    return Error::BAD_BUFFER;
+  }
+
+  if (hnd->base == 0) {
+    // we need to map for real
+    err = MapBuffer(hnd);
+  }
+
+  // Invalidate if CPU reads in software and there are non-CPU
+  // writers. No need to do this for the metadata buffer as it is
+  // only read/written in software.
+
+  // todo use handle here
+  if (err == Error::NONE && (hnd->flags & private_handle_t::PRIV_FLAGS_USES_ION) &&
+      (hnd->flags & private_handle_t::PRIV_FLAGS_CACHED)) {
+    if (allocator_->CleanBuffer(reinterpret_cast<void *>(hnd->base), hnd->size, hnd->offset,
+                                buf->ion_handle_main, CACHE_INVALIDATE)) {
+      return Error::BAD_BUFFER;
+    }
+  }
+
+  // Mark the buffer to be flushed after CPU write.
+  if (err == Error::NONE && CpuCanWrite(usage)) {
+    private_handle_t *handle = const_cast<private_handle_t *>(hnd);
+    handle->flags |= private_handle_t::PRIV_FLAGS_NEEDS_FLUSH;
+  }
+
+  return err;
+}
+
+Error BufferManager::UnlockBuffer(const private_handle_t *handle) {
+  std::lock_guard<std::mutex> lock(buffer_lock_);
+  auto status = Error::NONE;
+
+  private_handle_t *hnd = const_cast<private_handle_t *>(handle);
+  auto buf = GetBufferFromHandleLocked(hnd);
+  if (buf == nullptr) {
+    return Error::BAD_BUFFER;
+  }
+
+  if (hnd->flags & private_handle_t::PRIV_FLAGS_NEEDS_FLUSH) {
+    if (allocator_->CleanBuffer(reinterpret_cast<void *>(hnd->base), hnd->size, hnd->offset,
+                                buf->ion_handle_main, CACHE_CLEAN) != 0) {
+      status = Error::BAD_BUFFER;
+    }
+    hnd->flags &= ~private_handle_t::PRIV_FLAGS_NEEDS_FLUSH;
+  }
+
+  return status;
+}
+
+uint32_t BufferManager::GetDataAlignment(int format, uint64_t usage) {
+  uint32_t align = UINT(getpagesize());
+  if (format == HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED) {
+    align = 8192;
+  }
+
+  if (usage & BufferUsage::PROTECTED) {
+    if ((usage & BufferUsage::CAMERA_OUTPUT) || (usage & GRALLOC_USAGE_PRIVATE_SECURE_DISPLAY)) {
+      // The alignment here reflects qsee mmu V7L/V8L requirement
+      align = SZ_2M;
+    } else {
+      align = SECURE_ALIGN;
+    }
+  }
+
+  return align;
+}
+
+int BufferManager::GetHandleFlags(int format, uint64_t usage) {
+  int flags = 0;
+  if (usage & BufferUsage::VIDEO_ENCODER) {
+    flags |= private_handle_t::PRIV_FLAGS_VIDEO_ENCODER;
+  }
+
+  if (usage & BufferUsage::CAMERA_OUTPUT) {
+    flags |= private_handle_t::PRIV_FLAGS_CAMERA_WRITE;
+  }
+
+  if (usage & BufferUsage::CAMERA_INPUT) {
+    flags |= private_handle_t::PRIV_FLAGS_CAMERA_READ;
+  }
+
+  if (usage & BufferUsage::COMPOSER_OVERLAY) {
+    flags |= private_handle_t::PRIV_FLAGS_DISP_CONSUMER;
+  }
+
+  if (usage & BufferUsage::GPU_TEXTURE) {
+    flags |= private_handle_t::PRIV_FLAGS_HW_TEXTURE;
+  }
+
+  if (usage & GRALLOC_USAGE_PRIVATE_SECURE_DISPLAY) {
+    flags |= private_handle_t::PRIV_FLAGS_SECURE_DISPLAY;
+  }
+
+  if (IsUBwcEnabled(format, usage)) {
+    flags |= private_handle_t::PRIV_FLAGS_UBWC_ALIGNED;
+  }
+
+  if (usage & (BufferUsage::CPU_READ_MASK | BufferUsage::CPU_WRITE_MASK)) {
+    flags |= private_handle_t::PRIV_FLAGS_CPU_RENDERED;
+  }
+
+  if ((usage & (BufferUsage::VIDEO_ENCODER | BufferUsage::VIDEO_DECODER |
+                BufferUsage::CAMERA_OUTPUT | BufferUsage::GPU_RENDER_TARGET))) {
+    flags |= private_handle_t::PRIV_FLAGS_NON_CPU_WRITER;
+  }
+
+  if (!allocator_->UseUncached(usage)) {
+    flags |= private_handle_t::PRIV_FLAGS_CACHED;
+  }
+
+  return flags;
+}
+
+int BufferManager::GetBufferType(int inputFormat) {
+  int buffer_type = BUFFER_TYPE_VIDEO;
+  if (IsUncompressedRGBFormat(inputFormat)) {
+    // RGB formats
+    buffer_type = BUFFER_TYPE_UI;
+  }
+
+  return buffer_type;
+}
+
+Error BufferManager::AllocateBuffer(const BufferDescriptor &descriptor, buffer_handle_t *handle,
+                                    unsigned int bufferSize) {
+  if (!handle)
+    return Error::BAD_BUFFER;
+  std::lock_guard<std::mutex> buffer_lock(buffer_lock_);
+
+  uint64_t usage = descriptor.GetUsage();
+  int format = allocator_->GetImplDefinedFormat(usage, descriptor.GetFormat());
+  uint32_t layer_count = descriptor.GetLayerCount();
+
+  unsigned int size;
+  unsigned int alignedw, alignedh;
+
+  int buffer_type = GetBufferType(format);
+  BufferInfo info = GetBufferInfo(descriptor);
+  info.format = format;
+  GetBufferSizeAndDimensions(info, &size, &alignedw, &alignedh);
+  size = (bufferSize >= size) ? bufferSize : size;
+
+  int err = 0;
+  int flags = 0;
+  auto page_size = UINT(getpagesize());
+  AllocData data;
+  data.align = GetDataAlignment(format, usage);
+  size = ALIGN(size, data.align) * layer_count;
+  data.size = size;
+  data.handle = (uintptr_t)handle;
+  data.uncached = allocator_->UseUncached(usage);
+
+  // Allocate buffer memory
+  err = allocator_->AllocateMem(&data, usage);
+  if (err) {
+    ALOGE("gralloc failed to allocate err=%s", strerror(-err));
+    return Error::NO_RESOURCES;
+  }
+
+  // Allocate memory for MetaData
+  AllocData e_data;
+  e_data.size = ALIGN(UINT(sizeof(MetaData_t)), page_size);
+  e_data.handle = data.handle;
+  e_data.align = page_size;
+
+  err = allocator_->AllocateMem(&e_data, 0);
+  if (err) {
+    ALOGE("gralloc failed to allocate metadata error=%s", strerror(-err));
+    return Error::NO_RESOURCES;
+  }
+
+  flags = GetHandleFlags(format, usage);
+  flags |= data.alloc_type;
+
+  // Create handle
+  private_handle_t *hnd = new private_handle_t(
+      data.fd, e_data.fd, flags, INT(alignedw), INT(alignedh), descriptor.GetWidth(),
+      descriptor.GetHeight(), format, buffer_type, data.size, usage);
+
+  hnd->id = ++next_id_;
+  hnd->base = 0;
+  hnd->base_metadata = 0;
+  hnd->layer_count = layer_count;
+
+  ColorSpace_t colorSpace = ITU_R_601;
+  setMetaData(hnd, UPDATE_COLOR_SPACE, reinterpret_cast<void *>(&colorSpace));
+  *handle = hnd;
+  RegisterHandleLocked(hnd, data.ion_handle, e_data.ion_handle);
+  ALOGD_IF(DEBUG, "Allocated buffer handle: %p id: %" PRIu64, hnd, hnd->id);
+  if (DEBUG) {
+    private_handle_t::Dump(hnd);
+  }
+  return Error::NONE;
+}
+
+Error BufferManager::Dump(std::ostringstream *os) {
+  for (auto it : handles_map_) {
+    auto buf = it.second;
+    auto hnd = buf->handle;
+    *os << "handle id: " << std::setw(4) << hnd->id;
+    *os << " fd: " << std::setw(3) << hnd->fd;
+    *os << " fd_meta: " << std::setw(3) << hnd->fd_metadata;
+    *os << " wxh: " << std::setw(4) << hnd->width << " x " << std::setw(4) << hnd->height;
+    *os << " uwxuh: " << std::setw(4) << hnd->unaligned_width << " x ";
+    *os << std::setw(4) << hnd->unaligned_height;
+    *os << " size: " << std::setw(9) << hnd->size;
+    *os << std::hex << std::setfill('0');
+    *os << " priv_flags: "
+        << "0x" << std::setw(8) << hnd->flags;
+    *os << " usage: "
+        << "0x" << std::setw(8) << hnd->usage;
+    // TODO(user): get format string from qdutils
+    *os << " format: "
+        << "0x" << std::setw(8) << hnd->format;
+    *os << std::dec << std::setfill(' ') << std::endl;
+  }
+  return Error::NONE;
+}
+}  //  namespace gralloc
diff --git a/gralloc/gr_buf_mgr.h b/gralloc/gr_buf_mgr.h
new file mode 100644
index 0000000..24b4c23
--- /dev/null
+++ b/gralloc/gr_buf_mgr.h
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2011-2018, The Linux Foundation. All rights reserved.
+ * Not a Contribution
+ *
+ * Copyright (C) 2008 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 __GR_BUF_MGR_H__
+#define __GR_BUF_MGR_H__
+
+#include <pthread.h>
+#include <mutex>
+#include <unordered_map>
+#include <unordered_set>
+#include <utility>
+
+#include "gr_allocator.h"
+#include "gr_buf_descriptor.h"
+#include "gralloc_priv.h"
+
+namespace gralloc {
+
+using android::hardware::graphics::mapper::V2_0::Error;
+
+class BufferManager {
+ public:
+  ~BufferManager();
+
+  Error AllocateBuffer(const BufferDescriptor &descriptor, buffer_handle_t *handle,
+                       unsigned int bufferSize = 0);
+  Error RetainBuffer(private_handle_t const *hnd);
+  Error ReleaseBuffer(private_handle_t const *hnd);
+  Error LockBuffer(const private_handle_t *hnd, uint64_t usage);
+  Error UnlockBuffer(const private_handle_t *hnd);
+  Error Dump(std::ostringstream *os);
+  static BufferManager *GetInstance();
+
+ private:
+  BufferManager();
+  Error MapBuffer(private_handle_t const *hnd);
+  int GetBufferType(int format);
+  uint32_t GetDataAlignment(int format, uint64_t usage);
+  int GetHandleFlags(int format, uint64_t usage);
+
+  // Imports the ion fds into the current process. Returns an error for invalid handles
+  Error ImportHandleLocked(private_handle_t *hnd);
+
+  // Creates a Buffer from the valid private handle and adds it to the map
+  void RegisterHandleLocked(const private_handle_t *hnd, int ion_handle, int ion_handle_meta);
+
+  // Wrapper structure over private handle
+  // Values associated with the private handle
+  // that do not need to go over IPC can be placed here
+  // This structure is also not expected to be ABI stable
+  // unlike private_handle_t
+  struct Buffer {
+    const private_handle_t *handle = nullptr;
+    int ref_count = 1;
+    // Hold the main and metadata ion handles
+    // Freed from the allocator process
+    // and unused in the mapping process
+    int ion_handle_main = -1;
+    int ion_handle_meta = -1;
+
+    Buffer() = delete;
+    explicit Buffer(const private_handle_t *h, int ih_main = -1, int ih_meta = -1)
+        : handle(h), ion_handle_main(ih_main), ion_handle_meta(ih_meta) {}
+    void IncRef() { ++ref_count; }
+    bool DecRef() { return --ref_count == 0; }
+  };
+
+  Error FreeBuffer(std::shared_ptr<Buffer> buf);
+
+  // Get the wrapper Buffer object from the handle, returns nullptr if handle is not found
+  std::shared_ptr<Buffer> GetBufferFromHandleLocked(const private_handle_t *hnd);
+
+  bool map_fb_mem_ = false;
+  Allocator *allocator_ = NULL;
+  std::mutex buffer_lock_;
+  std::unordered_map<const private_handle_t *, std::shared_ptr<Buffer>> handles_map_ = {};
+  std::atomic<uint64_t> next_id_;
+};
+
+}  // namespace gralloc
+
+#endif  // __GR_BUF_MGR_H__
diff --git a/gralloc/gr_device_impl.cpp b/gralloc/gr_device_impl.cpp
new file mode 100644
index 0000000..a26ea81
--- /dev/null
+++ b/gralloc/gr_device_impl.cpp
@@ -0,0 +1,869 @@
+/*
+ * Copyright (c) 2016-2018, The Linux Foundation. All rights reserved.
+
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *   * Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *   * Redistributions in binary form must reproduce the above
+ *     copyright notice, this list of conditions and the following
+ *     disclaimer in the documentation and/or other materials provided
+ *     with the distribution.
+ *   * Neither the name of The Linux Foundation nor the names of its
+ *     contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+ * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#define ATRACE_TAG (ATRACE_TAG_GRAPHICS | ATRACE_TAG_HAL)
+#include <log/log.h>
+#include <cutils/trace.h>
+#include <sync/sync.h>
+#include <utils/Trace.h>
+#include <algorithm>
+#include <sstream>
+#include <string>
+
+#include "gr_buf_descriptor.h"
+#include "gr_device_impl.h"
+#include "gr_utils.h"
+#include "gralloc_priv.h"
+#include "qdMetaData.h"
+#include "qd_utils.h"
+
+int gralloc_device_open(const struct hw_module_t *module, const char *name, hw_device_t **device);
+
+int gralloc_device_close(struct hw_device_t *device);
+
+static struct hw_module_methods_t gralloc_module_methods = {.open = gralloc_device_open};
+
+struct gralloc_module_t HAL_MODULE_INFO_SYM = {
+    // clang-format off
+    .common = {
+            .tag = HARDWARE_MODULE_TAG,
+            .module_api_version = GRALLOC_MODULE_API_VERSION_1_0,
+            .hal_api_version = HARDWARE_HAL_API_VERSION,
+            .id = GRALLOC_HARDWARE_MODULE_ID,
+            .name = "Graphics Memory Module",
+            .author = "Code Aurora Forum",
+            .methods = &gralloc_module_methods,
+            .dso = 0,
+            .reserved = {0},
+        },
+    // clang-format on
+};
+
+int gralloc_device_open(const struct hw_module_t *module, const char *name, hw_device_t **device) {
+  int status = -EINVAL;
+  if (module && device && !strcmp(name, GRALLOC_HARDWARE_MODULE_ID)) {
+    gralloc::GrallocImpl * /*gralloc1_device_t*/ dev = gralloc::GrallocImpl::GetInstance(module);
+    *device = reinterpret_cast<hw_device_t *>(dev);
+    if (dev) {
+      status = 0;
+    } else {
+      ALOGE("Fatal error opening gralloc1 device");
+    }
+  }
+  return status;
+}
+
+namespace gralloc {
+
+std::atomic<uint64_t> GrallocImpl::next_descriptor_id_(1);
+
+GrallocImpl::GrallocImpl(const hw_module_t *module) {
+  common.tag = HARDWARE_DEVICE_TAG;
+  common.version = GRALLOC_MODULE_API_VERSION_1_0;
+  common.module = const_cast<hw_module_t *>(module);
+  common.close = CloseDevice;
+  getFunction = GetFunction;
+  getCapabilities = GetCapabilities;
+
+  initialized_ = Init();
+}
+
+inline gralloc1_error_t ToError(Error error) {
+  switch (error) {
+    case Error::NONE:
+      return GRALLOC1_ERROR_NONE;
+    case Error::BAD_DESCRIPTOR:
+      return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+    case Error::BAD_BUFFER:
+      return GRALLOC1_ERROR_BAD_HANDLE;
+    case Error::BAD_VALUE:
+      return GRALLOC1_ERROR_BAD_VALUE;
+    case Error::NO_RESOURCES:
+      return GRALLOC1_ERROR_NO_RESOURCES;
+    case Error::UNSUPPORTED:
+    default:
+      return GRALLOC1_ERROR_UNSUPPORTED;
+  }
+}
+
+static uint64_t ProducerUsageToBufferUsage(gralloc1_producer_usage_t producer_usage) {
+  uint64_t usage = producer_usage & ~(GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN |
+                                      GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN);
+  if ((producer_usage & GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN) ==
+      GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN) {
+    usage |= BufferUsage::CPU_READ_OFTEN;
+  } else if ((producer_usage & GRALLOC1_PRODUCER_USAGE_CPU_READ) ==
+             GRALLOC1_PRODUCER_USAGE_CPU_READ) {
+    usage |= BufferUsage::CPU_READ_RARELY;
+  }
+
+  if ((producer_usage & GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN) ==
+      GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN) {
+    usage |= BufferUsage::CPU_WRITE_OFTEN;
+  } else if ((producer_usage & GRALLOC1_PRODUCER_USAGE_CPU_WRITE) ==
+             GRALLOC1_PRODUCER_USAGE_CPU_WRITE) {
+    usage |= BufferUsage::CPU_WRITE_RARELY;
+  }
+  return usage;
+}
+
+static uint64_t ConsumerUsageToBufferUsage(gralloc1_consumer_usage_t consumer_usage) {
+  uint64_t usage = consumer_usage & ~(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN);
+  if ((consumer_usage & GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) ==
+      GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) {
+    usage |= BufferUsage::CPU_READ_OFTEN;
+  } else if ((consumer_usage & GRALLOC1_CONSUMER_USAGE_CPU_READ) ==
+             GRALLOC1_CONSUMER_USAGE_CPU_READ) {
+    usage |= BufferUsage::CPU_READ_RARELY;
+  }
+  return usage;
+}
+
+bool GrallocImpl::Init() {
+  buf_mgr_ = BufferManager::GetInstance();
+  return buf_mgr_ != nullptr;
+}
+
+GrallocImpl::~GrallocImpl() {}
+
+gralloc1_error_t GrallocImpl::CreateBufferDescriptorLocked(
+    gralloc1_buffer_descriptor_t *descriptor_id) {
+  std::lock_guard<std::mutex> lock(descriptor_lock_);
+  auto descriptor = std::make_shared<BufferDescriptor>(next_descriptor_id_++);
+  *descriptor_id = static_cast<gralloc1_buffer_descriptor_t>(descriptor->GetId());
+  descriptors_map_.emplace(*descriptor_id, descriptor);
+  return GRALLOC1_ERROR_NONE;
+}
+
+gralloc1_error_t GrallocImpl::DestroyBufferDescriptorLocked(
+    gralloc1_buffer_descriptor_t descriptor_id) {
+  std::lock_guard<std::mutex> lock(descriptor_lock_);
+  const auto descriptor = descriptors_map_.find(descriptor_id);
+  if (descriptor == descriptors_map_.end()) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  }
+  descriptors_map_.erase(descriptor);
+  return GRALLOC1_ERROR_NONE;
+}
+
+int GrallocImpl::CloseDevice(hw_device_t *device __unused) {
+  // No-op since the gralloc device is a singleton
+  return 0;
+}
+
+void GrallocImpl::GetCapabilities(struct gralloc1_device *device, uint32_t *out_count,
+                                  int32_t /*gralloc1_capability_t*/ *out_capabilities) {
+  if (device != nullptr && out_count != nullptr) {
+    if (out_capabilities != nullptr && *out_count >= 3) {
+      out_capabilities[0] = GRALLOC1_CAPABILITY_TEST_ALLOCATE;
+      out_capabilities[1] = GRALLOC1_CAPABILITY_LAYERED_BUFFERS;
+      out_capabilities[2] = GRALLOC1_CAPABILITY_RELEASE_IMPLY_DELETE;
+    }
+    *out_count = 3;
+  }
+  return;
+}
+
+gralloc1_function_pointer_t GrallocImpl::GetFunction(gralloc1_device_t *device, int32_t function) {
+  if (!device) {
+    return NULL;
+  }
+
+  switch (function) {
+    case GRALLOC1_FUNCTION_DUMP:
+      return reinterpret_cast<gralloc1_function_pointer_t>(Dump);
+    case GRALLOC1_FUNCTION_CREATE_DESCRIPTOR:
+      return reinterpret_cast<gralloc1_function_pointer_t>(CreateBufferDescriptor);
+    case GRALLOC1_FUNCTION_DESTROY_DESCRIPTOR:
+      return reinterpret_cast<gralloc1_function_pointer_t>(DestroyBufferDescriptor);
+    case GRALLOC1_FUNCTION_SET_CONSUMER_USAGE:
+      return reinterpret_cast<gralloc1_function_pointer_t>(SetConsumerUsage);
+    case GRALLOC1_FUNCTION_SET_DIMENSIONS:
+      return reinterpret_cast<gralloc1_function_pointer_t>(SetBufferDimensions);
+    case GRALLOC1_FUNCTION_SET_FORMAT:
+      return reinterpret_cast<gralloc1_function_pointer_t>(SetColorFormat);
+    case GRALLOC1_FUNCTION_SET_LAYER_COUNT:
+      return reinterpret_cast<gralloc1_function_pointer_t>(SetLayerCount);
+    case GRALLOC1_FUNCTION_SET_PRODUCER_USAGE:
+      return reinterpret_cast<gralloc1_function_pointer_t>(SetProducerUsage);
+    case GRALLOC1_FUNCTION_GET_BACKING_STORE:
+      return reinterpret_cast<gralloc1_function_pointer_t>(GetBackingStore);
+    case GRALLOC1_FUNCTION_GET_CONSUMER_USAGE:
+      return reinterpret_cast<gralloc1_function_pointer_t>(GetConsumerUsage);
+    case GRALLOC1_FUNCTION_GET_DIMENSIONS:
+      return reinterpret_cast<gralloc1_function_pointer_t>(GetBufferDimensions);
+    case GRALLOC1_FUNCTION_GET_FORMAT:
+      return reinterpret_cast<gralloc1_function_pointer_t>(GetColorFormat);
+    case GRALLOC1_FUNCTION_GET_LAYER_COUNT:
+      return reinterpret_cast<gralloc1_function_pointer_t>(GetLayerCount);
+    case GRALLOC1_FUNCTION_GET_PRODUCER_USAGE:
+      return reinterpret_cast<gralloc1_function_pointer_t>(GetProducerUsage);
+    case GRALLOC1_FUNCTION_GET_STRIDE:
+      return reinterpret_cast<gralloc1_function_pointer_t>(GetBufferStride);
+    case GRALLOC1_FUNCTION_ALLOCATE:
+      return reinterpret_cast<gralloc1_function_pointer_t>(AllocateBuffers);
+    case GRALLOC1_FUNCTION_RETAIN:
+      return reinterpret_cast<gralloc1_function_pointer_t>(RetainBuffer);
+    case GRALLOC1_FUNCTION_RELEASE:
+      return reinterpret_cast<gralloc1_function_pointer_t>(ReleaseBuffer);
+    case GRALLOC1_FUNCTION_GET_NUM_FLEX_PLANES:
+      return reinterpret_cast<gralloc1_function_pointer_t>(GetNumFlexPlanes);
+    case GRALLOC1_FUNCTION_LOCK:
+      return reinterpret_cast<gralloc1_function_pointer_t>(LockBuffer);
+    case GRALLOC1_FUNCTION_LOCK_FLEX:
+      return reinterpret_cast<gralloc1_function_pointer_t>(LockFlex);
+    case GRALLOC1_FUNCTION_UNLOCK:
+      return reinterpret_cast<gralloc1_function_pointer_t>(UnlockBuffer);
+    case GRALLOC1_FUNCTION_PERFORM:
+      return reinterpret_cast<gralloc1_function_pointer_t>(Gralloc1Perform);
+    default:
+      ALOGE("%s:Gralloc Error. Client Requested for unsupported function", __FUNCTION__);
+      return NULL;
+  }
+
+  return NULL;
+}
+
+gralloc1_error_t GrallocImpl::Dump(gralloc1_device_t *device, uint32_t *out_size,
+                                   char *out_buffer) {
+  if (!device || !out_size) {
+    ALOGE("Gralloc Error : device=%p", (void *)device);
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  }
+  const size_t max_dump_size = 8192;
+  if (out_buffer == nullptr) {
+    *out_size = max_dump_size;
+  } else {
+    std::ostringstream os;
+    os << "-------------------------------" << std::endl;
+    os << "QTI gralloc dump:" << std::endl;
+    os << "-------------------------------" << std::endl;
+    GrallocImpl const *dev = GRALLOC_IMPL(device);
+    dev->buf_mgr_->Dump(&os);
+    os << "-------------------------------" << std::endl;
+    auto copied = os.str().copy(out_buffer, std::min(os.str().size(), max_dump_size), 0);
+    *out_size = UINT(copied);
+  }
+
+  return GRALLOC1_ERROR_NONE;
+}
+
+gralloc1_error_t GrallocImpl::CheckDeviceAndHandle(gralloc1_device_t *device,
+                                                   buffer_handle_t buffer) {
+  const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
+  if (!device || (private_handle_t::validate(hnd) != 0)) {
+    ALOGE("Gralloc Error : device= %p, buffer-handle=%p", (void *)device, (void *)buffer);
+    return GRALLOC1_ERROR_BAD_HANDLE;
+  }
+
+  return GRALLOC1_ERROR_NONE;
+}
+
+gralloc1_error_t GrallocImpl::CreateBufferDescriptor(gralloc1_device_t *device,
+                                                     gralloc1_buffer_descriptor_t *out_descriptor) {
+  if (!device || !out_descriptor) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  }
+  auto *dev = reinterpret_cast<GrallocImpl *>(device);
+  return dev->CreateBufferDescriptorLocked(out_descriptor);
+}
+
+gralloc1_error_t GrallocImpl::DestroyBufferDescriptor(gralloc1_device_t *device,
+                                                      gralloc1_buffer_descriptor_t descriptor) {
+  if (!device) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  }
+  auto *dev = reinterpret_cast<GrallocImpl *>(device);
+  return dev->DestroyBufferDescriptorLocked(descriptor);
+}
+
+gralloc1_error_t GrallocImpl::SetConsumerUsage(gralloc1_device_t *device,
+                                               gralloc1_buffer_descriptor_t descriptor,
+                                               gralloc1_consumer_usage_t usage) {
+  if (!device) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  } else {
+    auto *dev = reinterpret_cast<GrallocImpl *>(device);
+    return dev->CallBufferDescriptorFunction(descriptor, &BufferDescriptor::SetUsage,
+                                             ConsumerUsageToBufferUsage(usage));
+  }
+}
+
+gralloc1_error_t GrallocImpl::SetBufferDimensions(gralloc1_device_t *device,
+                                                  gralloc1_buffer_descriptor_t descriptor,
+                                                  uint32_t width, uint32_t height) {
+  if (!device) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  } else {
+    auto *dev = reinterpret_cast<GrallocImpl *>(device);
+    return dev->CallBufferDescriptorFunction(descriptor, &BufferDescriptor::SetDimensions,
+                                             INT(width), INT(height));
+  }
+}
+
+gralloc1_error_t GrallocImpl::SetColorFormat(gralloc1_device_t *device,
+                                             gralloc1_buffer_descriptor_t descriptor,
+                                             int32_t format) {
+  if (!device) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  } else {
+    auto *dev = reinterpret_cast<GrallocImpl *>(device);
+    return dev->CallBufferDescriptorFunction(descriptor, &BufferDescriptor::SetColorFormat, format);
+  }
+}
+
+gralloc1_error_t GrallocImpl::SetLayerCount(gralloc1_device_t *device,
+                                            gralloc1_buffer_descriptor_t descriptor,
+                                            uint32_t layer_count) {
+  if (!device) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  } else {
+    auto *dev = reinterpret_cast<GrallocImpl *>(device);
+    return dev->CallBufferDescriptorFunction(descriptor, &BufferDescriptor::SetLayerCount,
+                                             layer_count);
+  }
+}
+
+gralloc1_error_t GrallocImpl::SetProducerUsage(gralloc1_device_t *device,
+                                               gralloc1_buffer_descriptor_t descriptor,
+                                               gralloc1_producer_usage_t usage) {
+  if (!device) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  } else {
+    auto *dev = reinterpret_cast<GrallocImpl *>(device);
+    return dev->CallBufferDescriptorFunction(descriptor, &BufferDescriptor::SetUsage,
+                                             ProducerUsageToBufferUsage(usage));
+  }
+}
+
+gralloc1_error_t GrallocImpl::GetBackingStore(gralloc1_device_t *device, buffer_handle_t buffer,
+                                              gralloc1_backing_store_t *out_backstore) {
+  if (!device || !buffer) {
+    return GRALLOC1_ERROR_BAD_HANDLE;
+  }
+
+  *out_backstore =
+      static_cast<gralloc1_backing_store_t>(PRIV_HANDLE_CONST(buffer)->GetBackingstore());
+
+  return GRALLOC1_ERROR_NONE;
+}
+
+gralloc1_error_t GrallocImpl::GetConsumerUsage(gralloc1_device_t *device, buffer_handle_t buffer,
+                                               gralloc1_consumer_usage_t *outUsage) {
+  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
+  if (status == GRALLOC1_ERROR_NONE) {
+    *outUsage = static_cast<gralloc1_consumer_usage_t>(PRIV_HANDLE_CONST(buffer)->GetUsage());
+  }
+
+  return status;
+}
+
+gralloc1_error_t GrallocImpl::GetBufferDimensions(gralloc1_device_t *device, buffer_handle_t buffer,
+                                                  uint32_t *outWidth, uint32_t *outHeight) {
+  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
+  if (status == GRALLOC1_ERROR_NONE) {
+    const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
+    *outWidth = UINT(hnd->GetUnalignedWidth());
+    *outHeight = UINT(hnd->GetUnalignedHeight());
+  }
+
+  return status;
+}
+
+gralloc1_error_t GrallocImpl::GetColorFormat(gralloc1_device_t *device, buffer_handle_t buffer,
+                                             int32_t *outFormat) {
+  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
+  if (status == GRALLOC1_ERROR_NONE) {
+    *outFormat = PRIV_HANDLE_CONST(buffer)->GetColorFormat();
+  }
+
+  return status;
+}
+
+gralloc1_error_t GrallocImpl::GetLayerCount(gralloc1_device_t *device, buffer_handle_t buffer,
+                                            uint32_t *outLayerCount) {
+  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
+  if (status == GRALLOC1_ERROR_NONE) {
+    *outLayerCount = PRIV_HANDLE_CONST(buffer)->GetLayerCount();
+  }
+
+  return status;
+}
+
+gralloc1_error_t GrallocImpl::GetProducerUsage(gralloc1_device_t *device, buffer_handle_t buffer,
+                                               gralloc1_producer_usage_t *outUsage) {
+  if (!outUsage) {
+    return GRALLOC1_ERROR_BAD_VALUE;
+  }
+
+  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
+  if (status == GRALLOC1_ERROR_NONE) {
+    *outUsage = static_cast<gralloc1_producer_usage_t>(PRIV_HANDLE_CONST(buffer)->GetUsage());
+  }
+
+  return status;
+}
+
+gralloc1_error_t GrallocImpl::GetBufferStride(gralloc1_device_t *device, buffer_handle_t buffer,
+                                              uint32_t *outStride) {
+  if (!outStride) {
+    return GRALLOC1_ERROR_BAD_VALUE;
+  }
+
+  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
+  if (status == GRALLOC1_ERROR_NONE) {
+    *outStride = UINT(PRIV_HANDLE_CONST(buffer)->GetStride());
+  }
+
+  return status;
+}
+
+gralloc1_error_t GrallocImpl::AllocateBuffer(const gralloc1_buffer_descriptor_t *descriptor_ids,
+                                             buffer_handle_t *out_buffers) {
+  gralloc1_error_t status = GRALLOC1_ERROR_NONE;
+
+  // Validate descriptor
+  std::lock_guard<std::mutex> descriptor_lock(descriptor_lock_);
+  std::shared_ptr<gralloc::BufferDescriptor> descriptor;
+  const auto map_descriptor = descriptors_map_.find(descriptor_ids[0]);
+  if (map_descriptor == descriptors_map_.end()) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  } else {
+    descriptor = map_descriptor->second;
+  }
+
+  // Allocate separate buffer for each descriptor
+  if (buf_mgr_->AllocateBuffer(*descriptor, &out_buffers[0]) != Error::NONE) {
+    return GRALLOC1_ERROR_NO_RESOURCES;
+  }
+
+  return status;
+}
+
+gralloc1_error_t GrallocImpl::AllocateBuffers(gralloc1_device_t *device, uint32_t num_descriptors,
+                                              const gralloc1_buffer_descriptor_t *descriptors,
+                                              buffer_handle_t *out_buffers) {
+  if (!num_descriptors || !descriptors) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  }
+
+  if (!device) {
+    return GRALLOC1_ERROR_BAD_VALUE;
+  }
+
+  if (num_descriptors != 1) {
+    return GRALLOC1_ERROR_UNSUPPORTED;
+  }
+
+  auto *dev = reinterpret_cast<GrallocImpl *>(device);
+  gralloc1_error_t status = dev->AllocateBuffer(descriptors, out_buffers);
+
+  return status;
+}
+
+gralloc1_error_t GrallocImpl::RetainBuffer(gralloc1_device_t *device, buffer_handle_t buffer) {
+  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
+  if (status == GRALLOC1_ERROR_NONE) {
+    const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
+    GrallocImpl const *dev = GRALLOC_IMPL(device);
+    status = ToError(dev->buf_mgr_->RetainBuffer(hnd));
+  }
+
+  return status;
+}
+
+gralloc1_error_t GrallocImpl::ReleaseBuffer(gralloc1_device_t *device, buffer_handle_t buffer) {
+  if (!device || !buffer) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  }
+
+  const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
+  GrallocImpl const *dev = GRALLOC_IMPL(device);
+  return ToError(dev->buf_mgr_->ReleaseBuffer(hnd));
+}
+
+gralloc1_error_t GrallocImpl::GetFlexLayout(const private_handle_t *hnd,
+                                            struct android_flex_layout *layout) {
+  if (!IsYuvFormat(hnd)) {
+    return GRALLOC1_ERROR_UNSUPPORTED;
+  }
+
+  android_ycbcr yuvPlaneInfo[2];
+  int err = GetYUVPlaneInfo(hnd, yuvPlaneInfo);
+
+  if (err != 0) {
+    return GRALLOC1_ERROR_BAD_HANDLE;
+  }
+
+  layout->format = FLEX_FORMAT_YCbCr;
+  layout->num_planes = 3;
+
+  for (uint32_t i = 0; i < layout->num_planes; i++) {
+    layout->planes[i].bits_per_component = 8;
+    layout->planes[i].bits_used = 8;
+    layout->planes[i].h_increment = 1;
+    layout->planes[i].v_increment = 1;
+    layout->planes[i].h_subsampling = 2;
+    layout->planes[i].v_subsampling = 2;
+  }
+
+  // We are only returning flex layout for progressive or single field formats.
+  struct android_ycbcr ycbcr = yuvPlaneInfo[0];
+  layout->planes[0].top_left = static_cast<uint8_t *>(ycbcr.y);
+  layout->planes[0].component = FLEX_COMPONENT_Y;
+  layout->planes[0].v_increment = static_cast<int32_t>(ycbcr.ystride);
+
+  layout->planes[1].top_left = static_cast<uint8_t *>(ycbcr.cb);
+  layout->planes[1].component = FLEX_COMPONENT_Cb;
+  layout->planes[1].h_increment = static_cast<int32_t>(ycbcr.chroma_step);
+  layout->planes[1].v_increment = static_cast<int32_t>(ycbcr.cstride);
+
+  layout->planes[2].top_left = static_cast<uint8_t *>(ycbcr.cr);
+  layout->planes[2].component = FLEX_COMPONENT_Cr;
+  layout->planes[2].h_increment = static_cast<int32_t>(ycbcr.chroma_step);
+  layout->planes[2].v_increment = static_cast<int32_t>(ycbcr.cstride);
+  return GRALLOC1_ERROR_NONE;
+}
+
+gralloc1_error_t GrallocImpl::GetNumFlexPlanes(gralloc1_device_t *device, buffer_handle_t buffer,
+                                               uint32_t *out_num_planes) {
+  if (!out_num_planes) {
+    return GRALLOC1_ERROR_BAD_VALUE;
+  }
+
+  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
+  if (status == GRALLOC1_ERROR_NONE) {
+    const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
+    if (!IsYuvFormat(hnd)) {
+      status = GRALLOC1_ERROR_UNSUPPORTED;
+    } else {
+      *out_num_planes = 3;
+    }
+  }
+  return status;
+}
+
+static inline void CloseFdIfValid(int fd) {
+  if (fd > 0) {
+    close(fd);
+  }
+}
+
+gralloc1_error_t GrallocImpl::LockBuffer(gralloc1_device_t *device, buffer_handle_t buffer,
+                                         gralloc1_producer_usage_t prod_usage,
+                                         gralloc1_consumer_usage_t cons_usage,
+                                         const gralloc1_rect_t *region, void **out_data,
+                                         int32_t acquire_fence) {
+  ATRACE_CALL();
+  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
+  if (status != GRALLOC1_ERROR_NONE || !out_data ||
+      !region) {  // currently we ignore the region/rect client wants to lock
+    CloseFdIfValid(acquire_fence);
+    return status;
+  }
+
+  if (acquire_fence > 0) {
+    ATRACE_BEGIN("fence wait");
+    int error = sync_wait(acquire_fence, 1000);
+    ATRACE_END();
+    CloseFdIfValid(acquire_fence);
+    if (error < 0) {
+      ALOGE("%s: sync_wait timedout! error = %s", __FUNCTION__, strerror(errno));
+      return GRALLOC1_ERROR_UNDEFINED;
+    }
+  }
+
+  const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
+  GrallocImpl const *dev = GRALLOC_IMPL(device);
+
+  // Either producer usage or consumer usage must be *_USAGE_NONE
+  if ((prod_usage != GRALLOC1_PRODUCER_USAGE_NONE) &&
+      (cons_usage != GRALLOC1_CONSUMER_USAGE_NONE)) {
+    // Current gralloc1 clients do not satisfy this restriction.
+    // See b/33588773 for details
+    // return GRALLOC1_ERROR_BAD_VALUE;
+  }
+
+  status = ToError(dev->buf_mgr_->LockBuffer(
+      hnd, ProducerUsageToBufferUsage(prod_usage) | ConsumerUsageToBufferUsage(cons_usage)));
+  *out_data = reinterpret_cast<void *>(hnd->base);
+
+  return status;
+}
+
+gralloc1_error_t GrallocImpl::LockFlex(gralloc1_device_t *device, buffer_handle_t buffer,
+                                       gralloc1_producer_usage_t prod_usage,
+                                       gralloc1_consumer_usage_t cons_usage,
+                                       const gralloc1_rect_t *region,
+                                       struct android_flex_layout *out_flex_layout,
+                                       int32_t acquire_fence) {
+  if (!out_flex_layout) {
+    CloseFdIfValid(acquire_fence);
+    return GRALLOC1_ERROR_BAD_VALUE;
+  }
+
+  void *out_data{};
+  gralloc1_error_t status = GrallocImpl::LockBuffer(device, buffer, prod_usage, cons_usage, region,
+                                                    &out_data, acquire_fence);
+  if (status != GRALLOC1_ERROR_NONE) {
+    return status;
+  }
+
+  auto *dev = reinterpret_cast<GrallocImpl *>(device);
+  const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
+  dev->GetFlexLayout(hnd, out_flex_layout);
+  return status;
+}
+
+gralloc1_error_t GrallocImpl::UnlockBuffer(gralloc1_device_t *device, buffer_handle_t buffer,
+                                           int32_t *release_fence) {
+  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
+  if (status != GRALLOC1_ERROR_NONE) {
+    return status;
+  }
+
+  if (!release_fence) {
+    return GRALLOC1_ERROR_BAD_VALUE;
+  }
+
+  const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
+  GrallocImpl const *dev = GRALLOC_IMPL(device);
+
+  *release_fence = -1;
+
+  return ToError(dev->buf_mgr_->UnlockBuffer(hnd));
+}
+
+static gralloc1_error_t Perform(int operation, va_list args) {
+  switch (operation) {
+    case GRALLOC_MODULE_PERFORM_GET_STRIDE: {
+      int width = va_arg(args, int);
+      int format = va_arg(args, int);
+      int *stride = va_arg(args, int *);
+      unsigned int alignedw = 0, alignedh = 0;
+
+      if (!stride) {
+        return GRALLOC1_ERROR_BAD_VALUE;
+      }
+
+      BufferInfo info(width, width, format);
+      GetAlignedWidthAndHeight(info, &alignedw, &alignedh);
+      *stride = INT(alignedw);
+    } break;
+
+    case GRALLOC_MODULE_PERFORM_GET_CUSTOM_STRIDE_FROM_HANDLE: {
+      private_handle_t *hnd = va_arg(args, private_handle_t *);
+      int *stride = va_arg(args, int *);
+      if (private_handle_t::validate(hnd) != 0) {
+        return GRALLOC1_ERROR_BAD_HANDLE;
+      }
+
+      if (!stride) {
+        return GRALLOC1_ERROR_BAD_VALUE;
+      }
+
+      BufferDim_t buffer_dim;
+      if (getMetaData(hnd, GET_BUFFER_GEOMETRY, &buffer_dim) == 0) {
+        *stride = buffer_dim.sliceWidth;
+      } else {
+        *stride = hnd->width;
+      }
+    } break;
+
+    case GRALLOC_MODULE_PERFORM_GET_CUSTOM_STRIDE_AND_HEIGHT_FROM_HANDLE: {
+      private_handle_t *hnd = va_arg(args, private_handle_t *);
+      int *stride = va_arg(args, int *);
+      int *height = va_arg(args, int *);
+      if (private_handle_t::validate(hnd) != 0) {
+        return GRALLOC1_ERROR_BAD_HANDLE;
+      }
+
+      if (!stride || !height) {
+        return GRALLOC1_ERROR_BAD_VALUE;
+      }
+
+      GetCustomDimensions(hnd, stride, height);
+    } break;
+
+    case GRALLOC_MODULE_PERFORM_GET_ATTRIBUTES: {
+      int width = va_arg(args, int);
+      int height = va_arg(args, int);
+      int format = va_arg(args, int);
+      uint64_t usage = va_arg(args, uint64_t);
+      usage |= va_arg(args, uint64_t);
+
+      int *aligned_width = va_arg(args, int *);
+      int *aligned_height = va_arg(args, int *);
+      int *tile_enabled = va_arg(args, int *);
+      if (!aligned_width || !aligned_height || !tile_enabled) {
+        return GRALLOC1_ERROR_BAD_VALUE;
+      }
+
+      unsigned int alignedw, alignedh;
+      BufferInfo info(width, height, format, usage);
+      *tile_enabled = IsUBwcEnabled(format, usage);
+      GetAlignedWidthAndHeight(info, &alignedw, &alignedh);
+      *aligned_width = INT(alignedw);
+      *aligned_height = INT(alignedh);
+    } break;
+
+    case GRALLOC_MODULE_PERFORM_GET_COLOR_SPACE_FROM_HANDLE: {
+      private_handle_t *hnd = va_arg(args, private_handle_t *);
+      int *color_space = va_arg(args, int *);
+
+      if (private_handle_t::validate(hnd) != 0) {
+        return GRALLOC1_ERROR_BAD_HANDLE;
+      }
+
+      if (!color_space) {
+        return GRALLOC1_ERROR_BAD_VALUE;
+      }
+
+      *color_space = 0;
+      GetColorSpaceFromMetadata(hnd, color_space);
+    } break;
+    case GRALLOC_MODULE_PERFORM_GET_YUV_PLANE_INFO: {
+      private_handle_t *hnd = va_arg(args, private_handle_t *);
+      android_ycbcr *ycbcr = va_arg(args, struct android_ycbcr *);
+      if (private_handle_t::validate(hnd) != 0) {
+        return GRALLOC1_ERROR_BAD_HANDLE;
+      }
+
+      if (!ycbcr) {
+        return GRALLOC1_ERROR_BAD_VALUE;
+      }
+
+      if (GetYUVPlaneInfo(hnd, ycbcr)) {
+        return GRALLOC1_ERROR_UNDEFINED;
+      }
+    } break;
+
+    case GRALLOC_MODULE_PERFORM_GET_MAP_SECURE_BUFFER_INFO: {
+      private_handle_t *hnd = va_arg(args, private_handle_t *);
+      int *map_secure_buffer = va_arg(args, int *);
+
+      if (private_handle_t::validate(hnd) != 0) {
+        return GRALLOC1_ERROR_BAD_HANDLE;
+      }
+
+      if (!map_secure_buffer) {
+        return GRALLOC1_ERROR_BAD_VALUE;
+      }
+
+      if (getMetaData(hnd, GET_MAP_SECURE_BUFFER, map_secure_buffer) != 0) {
+        *map_secure_buffer = 0;
+      }
+    } break;
+
+    case GRALLOC_MODULE_PERFORM_GET_UBWC_FLAG: {
+      private_handle_t *hnd = va_arg(args, private_handle_t *);
+      int *flag = va_arg(args, int *);
+
+      if (private_handle_t::validate(hnd) != 0) {
+        return GRALLOC1_ERROR_BAD_HANDLE;
+      }
+
+      if (!flag) {
+        return GRALLOC1_ERROR_BAD_VALUE;
+      }
+
+      *flag = hnd->flags & private_handle_t::PRIV_FLAGS_UBWC_ALIGNED;
+      int linear_format = 0;
+      if (getMetaData(hnd, GET_LINEAR_FORMAT, &linear_format) == 0) {
+        if (linear_format) {
+          *flag = 0;
+        }
+      }
+    } break;
+
+    case GRALLOC_MODULE_PERFORM_GET_RGB_DATA_ADDRESS: {
+      private_handle_t *hnd = va_arg(args, private_handle_t *);
+      void **rgb_data = va_arg(args, void **);
+
+      if (private_handle_t::validate(hnd) != 0) {
+        return GRALLOC1_ERROR_BAD_HANDLE;
+      }
+
+      if (!rgb_data) {
+        return GRALLOC1_ERROR_BAD_VALUE;
+      }
+
+      if (GetRgbDataAddress(hnd, rgb_data)) {
+        return GRALLOC1_ERROR_UNDEFINED;
+      }
+    } break;
+
+    case GRALLOC1_MODULE_PERFORM_GET_INTERLACE_FLAG: {
+      private_handle_t *hnd = va_arg(args, private_handle_t *);
+      int *flag = va_arg(args, int *);
+
+      if (private_handle_t::validate(hnd) != 0) {
+        return GRALLOC1_ERROR_BAD_HANDLE;
+      }
+
+      if (!flag) {
+        return GRALLOC1_ERROR_BAD_VALUE;
+      }
+
+      if (getMetaData(hnd, GET_PP_PARAM_INTERLACED, flag) != 0) {
+        *flag = 0;
+      }
+    } break;
+
+    case GRALLOC_MODULE_PERFORM_SET_SINGLE_BUFFER_MODE: {
+      private_handle_t *hnd = va_arg(args, private_handle_t *);
+      uint32_t *enable = va_arg(args, uint32_t *);
+      if (private_handle_t::validate(hnd) != 0) {
+        return GRALLOC1_ERROR_BAD_HANDLE;
+      }
+      if (setMetaData(hnd, SET_SINGLE_BUFFER_MODE, enable) != 0) {
+        return GRALLOC1_ERROR_UNSUPPORTED;
+      }
+    } break;
+
+    default:
+      break;
+  }
+  return GRALLOC1_ERROR_NONE;
+}
+
+gralloc1_error_t GrallocImpl::Gralloc1Perform(gralloc1_device_t *device, int operation, ...) {
+  if (!device) {
+    return GRALLOC1_ERROR_BAD_VALUE;
+  }
+
+  va_list args;
+  va_start(args, operation);
+  gralloc1_error_t err = Perform(operation, args);
+  va_end(args);
+
+  return err;
+}
+
+}  // namespace gralloc
diff --git a/libgralloc1/gr_device_impl.h b/gralloc/gr_device_impl.h
similarity index 81%
rename from libgralloc1/gr_device_impl.h
rename to gralloc/gr_device_impl.h
index 55ce44b..82e9e71 100644
--- a/libgralloc1/gr_device_impl.h
+++ b/gralloc/gr_device_impl.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2016-2018, The Linux Foundation. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -30,8 +30,8 @@
 #ifndef __GR_DEVICE_IMPL_H__
 #define __GR_DEVICE_IMPL_H__
 
-#include <hardware/hardware.h>
 #include <hardware/gralloc1.h>
+#include <hardware/hardware.h>
 #include "gr_buf_mgr.h"
 
 struct private_module_t {
@@ -40,7 +40,7 @@
 
 #define GRALLOC_IMPL(exp) reinterpret_cast<GrallocImpl const *>(exp)
 
-namespace gralloc1 {
+namespace gralloc {
 
 class GrallocImpl : public gralloc1_device_t {
  public:
@@ -50,7 +50,7 @@
   static gralloc1_function_pointer_t GetFunction(
       struct gralloc1_device *device, int32_t /*gralloc1_function_descriptor_t*/ descriptor);
 
-  static GrallocImpl* GetInstance(const struct hw_module_t *module) {
+  static GrallocImpl *GetInstance(const struct hw_module_t *module) {
     static GrallocImpl *instance = new GrallocImpl(module);
     if (instance->IsInitialized()) {
       return instance;
@@ -119,15 +119,39 @@
                                        int32_t *release_fence);
   static gralloc1_error_t Gralloc1Perform(gralloc1_device_t *device, int operation, ...);
 
+  gralloc1_error_t CreateBufferDescriptorLocked(gralloc1_buffer_descriptor_t *descriptor_id);
+  gralloc1_error_t DestroyBufferDescriptorLocked(gralloc1_buffer_descriptor_t descriptor_id);
+  gralloc1_error_t AllocateBuffer(const gralloc1_buffer_descriptor_t *descriptor_ids,
+                                  buffer_handle_t *out_buffers);
+  gralloc1_error_t GetFlexLayout(const private_handle_t *hnd, struct android_flex_layout *layout);
+
+  template <typename... Args>
+  gralloc1_error_t CallBufferDescriptorFunction(gralloc1_buffer_descriptor_t descriptor_id,
+                                                void (BufferDescriptor::*member)(Args...),
+                                                Args... args) {
+    std::lock_guard<std::mutex> lock(descriptor_lock_);
+    const auto map_descriptor = descriptors_map_.find(descriptor_id);
+    if (map_descriptor == descriptors_map_.end()) {
+      return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+    }
+    const auto descriptor = map_descriptor->second;
+    (descriptor.get()->*member)(std::forward<Args>(args)...);
+    return GRALLOC1_ERROR_NONE;
+  }
+
   explicit GrallocImpl(const hw_module_t *module);
   ~GrallocImpl();
   bool Init();
-  bool IsInitialized() const { return initalized_; }
+  bool IsInitialized() const { return initialized_; }
 
   BufferManager *buf_mgr_ = NULL;
-  bool initalized_ = false;
+  bool initialized_ = false;
+  std::mutex descriptor_lock_;
+  std::unordered_map<gralloc1_buffer_descriptor_t, std::shared_ptr<gralloc::BufferDescriptor>>
+      descriptors_map_ = {};
+  static std::atomic<uint64_t> next_descriptor_id_;
 };
 
-}  // namespace gralloc1
+}  // namespace gralloc
 
 #endif  // __GR_DEVICE_IMPL_H__
diff --git a/libgralloc1/gr_ion_alloc.cpp b/gralloc/gr_ion_alloc.cpp
similarity index 96%
rename from libgralloc1/gr_ion_alloc.cpp
rename to gralloc/gr_ion_alloc.cpp
index c8300ab..33a13ab 100644
--- a/libgralloc1/gr_ion_alloc.cpp
+++ b/gralloc/gr_ion_alloc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2018, The Linux Foundation. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -29,21 +29,21 @@
 
 #define DEBUG 0
 #define ATRACE_TAG (ATRACE_TAG_GRAPHICS | ATRACE_TAG_HAL)
+#include <log/log.h>
+#include <cutils/trace.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdlib.h>
 #include <sys/ioctl.h>
 #include <sys/mman.h>
-#include <stdlib.h>
-#include <fcntl.h>
-#include <cutils/log.h>
-#include <errno.h>
 #include <utils/Trace.h>
-#include <cutils/trace.h>
 #include <string>
 
-#include "gralloc_priv.h"
-#include "gr_utils.h"
 #include "gr_ion_alloc.h"
+#include "gr_utils.h"
+#include "gralloc_priv.h"
 
-namespace gralloc1 {
+namespace gralloc {
 
 bool IonAlloc::Init() {
   if (ion_dev_fd_ == FD_INIT) {
@@ -105,8 +105,8 @@
 
   data->fd = fd_data.fd;
   data->ion_handle = handle_data.handle;
-  ALOGD_IF(DEBUG, "ion: Allocated buffer size:%zu fd:%d handle:0x%x",
-          ion_alloc_data.len, data->fd, data->ion_handle);
+  ALOGD_IF(DEBUG, "ion: Allocated buffer size:%zu fd:%d handle:0x%x", ion_alloc_data.len, data->fd,
+           data->ion_handle);
 
   return 0;
 }
@@ -210,4 +210,4 @@
   return 0;
 }
 
-}  // namespace gralloc1
+}  // namespace gralloc
diff --git a/libgralloc1/gr_ion_alloc.h b/gralloc/gr_ion_alloc.h
similarity index 95%
rename from libgralloc1/gr_ion_alloc.h
rename to gralloc/gr_ion_alloc.h
index b25f509..6a1fd7f 100644
--- a/libgralloc1/gr_ion_alloc.h
+++ b/gralloc/gr_ion_alloc.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2018, The Linux Foundation. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -34,7 +34,7 @@
 
 #define FD_INIT -1
 
-namespace gralloc1 {
+namespace gralloc {
 
 enum {
   CACHE_CLEAN = 0x1,
@@ -79,6 +79,6 @@
   int ion_dev_fd_;
 };
 
-}  // namespace gralloc1
+}  // namespace gralloc
 
 #endif  // __GR_ION_ALLOC_H__
diff --git a/libgralloc1/gr_priv_handle.h b/gralloc/gr_priv_handle.h
similarity index 68%
rename from libgralloc1/gr_priv_handle.h
rename to gralloc/gr_priv_handle.h
index 49e09a5..1eb03b8 100644
--- a/libgralloc1/gr_priv_handle.h
+++ b/gralloc/gr_priv_handle.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2018, The Linux Foundation. All rights reserved.
  * Not a Contribution
  *
  * Copyright (C) 2008 The Android Open Source Project
@@ -20,9 +20,9 @@
 #ifndef __GR_PRIV_HANDLE_H__
 #define __GR_PRIV_HANDLE_H__
 
-#include <cutils/log.h>
-#include <hardware/gralloc1.h>
+#include <log/log.h>
 #include <hardware/gralloc.h>
+#include <hardware/gralloc1.h>
 #include <cinttypes>
 
 #define GRALLOC1_FUNCTION_PERFORM 0x00001000
@@ -57,7 +57,7 @@
     PRIV_FLAGS_CPU_RENDERED = 0x04000000,
     PRIV_FLAGS_UBWC_ALIGNED = 0x08000000,
     PRIV_FLAGS_DISP_CONSUMER = 0x10000000,
-    PRIV_FLAGS_CLIENT_ALLOCATED = 0x20000000,   // Ion buffer allocated outside of gralloc
+    PRIV_FLAGS_CLIENT_ALLOCATED = 0x20000000,  // Ion buffer allocated outside of gralloc
   };
 
   // file-descriptors dup'd over IPC
@@ -67,43 +67,32 @@
   // values sent over IPC
   int magic;
   int flags;
-  int width;        // holds width of the actual buffer allocated
-  int height;       // holds height of the  actual buffer allocated
+  int width;             // holds width of the actual buffer allocated
+  int height;            // holds height of the  actual buffer allocated
   int unaligned_width;   // holds width client asked to allocate
   int unaligned_height;  // holds height client asked to allocate
   int format;
   int buffer_type;
+  unsigned int layer_count;
+  uint64_t id __attribute__((aligned(8)));
+  uint64_t usage __attribute__((aligned(8)));
+
   unsigned int size;
   unsigned int offset;
   unsigned int offset_metadata;
-  uint64_t base                            __attribute__((aligned(8)));
-  uint64_t base_metadata                   __attribute__((aligned(8)));
-  uint64_t gpuaddr                         __attribute__((aligned(8)));
-  uint64_t id                              __attribute__((aligned(8)));
-  gralloc1_producer_usage_t producer_usage __attribute__((aligned(8)));
-  gralloc1_consumer_usage_t consumer_usage __attribute__((aligned(8)));
-  unsigned int layer_count;
+  uint64_t base __attribute__((aligned(8)));
+  uint64_t base_metadata __attribute__((aligned(8)));
+  uint64_t gpuaddr __attribute__((aligned(8)));
 
   static const int kNumFds = 2;
   static const int kMagic = 'gmsm';
 
   static inline int NumInts() {
-    return ((sizeof(private_handle_t) - sizeof(native_handle_t)) / sizeof(int))
-        - kNumFds;
+    return ((sizeof(private_handle_t) - sizeof(native_handle_t)) / sizeof(int)) - kNumFds;
   }
 
-  private_handle_t(int fd,
-                   int meta_fd,
-                   int flags,
-                   int width,
-                   int height,
-                   int uw,
-                   int uh,
-                   int format,
-                   int buf_type,
-                   unsigned int size,
-                   gralloc1_producer_usage_t prod_usage = GRALLOC1_PRODUCER_USAGE_NONE,
-                   gralloc1_consumer_usage_t cons_usage = GRALLOC1_CONSUMER_USAGE_NONE)
+  private_handle_t(int fd, int meta_fd, int flags, int width, int height, int uw, int uh,
+                   int format, int buf_type, unsigned int size, uint64_t usage = 0)
       : fd(fd),
         fd_metadata(meta_fd),
         magic(kMagic),
@@ -114,27 +103,24 @@
         unaligned_height(uh),
         format(format),
         buffer_type(buf_type),
+        layer_count(1),
+        id(0),
+        usage(usage),
         size(size),
         offset(0),
         offset_metadata(0),
         base(0),
         base_metadata(0),
-        gpuaddr(0),
-        id(0),
-        producer_usage(prod_usage),
-        consumer_usage(cons_usage),
-        layer_count(1) {
+        gpuaddr(0) {
     version = static_cast<int>(sizeof(native_handle));
     numInts = NumInts();
     numFds = kNumFds;
   }
 
-// Legacy constructor used by some clients
+  // Legacy constructor used by some clients
   private_handle_t(int fd, unsigned int size, int usage, int buf_type, int format, int w, int h)
-  : private_handle_t(fd, -1, PRIV_FLAGS_CLIENT_ALLOCATED, w, h, 0, 0, format, buf_type, size,
-                     static_cast<gralloc1_producer_usage_t>(usage),
-                     static_cast<gralloc1_consumer_usage_t>(usage)) {
-  }
+      : private_handle_t(fd, -1, PRIV_FLAGS_CLIENT_ALLOCATED, w, h, 0, 0, format, buf_type, size,
+                         static_cast<uint64_t>(usage)) {}
 
   ~private_handle_t() {
     magic = 0;
@@ -142,7 +128,7 @@
   }
 
   static int validate(const native_handle *h) {
-    const private_handle_t *hnd = (const private_handle_t *)h;
+    auto *hnd = static_cast<const private_handle_t *>(h);
     if (!h || h->version != sizeof(native_handle) || h->numInts != NumInts() ||
         h->numFds != kNumFds || hnd->magic != kMagic) {
       ALOGE(
@@ -162,11 +148,11 @@
   }
 
   static void Dump(const private_handle_t *hnd) {
-    ALOGD("handle id:%" PRIu64 " wxh:%dx%d uwxuh:%dx%d size: %d fd:%d fd_meta:%d flags:0x%x "
-          "prod_usage:0x%" PRIx64" cons_usage:0x%" PRIx64 " format:0x%x layer_count: %d",
+    ALOGD("handle id:%" PRIu64
+          " wxh:%dx%d uwxuh:%dx%d size: %d fd:%d fd_meta:%d flags:0x%x "
+          "usage:0x%" PRIx64 "  format:0x%x layer_count: %d",
           hnd->id, hnd->width, hnd->height, hnd->unaligned_width, hnd->unaligned_height, hnd->size,
-          hnd->fd, hnd->fd_metadata, hnd->flags, hnd->producer_usage, hnd->consumer_usage,
-          hnd->format, hnd->layer_count);
+          hnd->fd, hnd->fd_metadata, hnd->flags, hnd->usage, hnd->format, hnd->layer_count);
   }
 
   int GetUnalignedWidth() const { return unaligned_width; }
@@ -182,9 +168,7 @@
     return width;
   }
 
-  gralloc1_consumer_usage_t GetConsumerUsage() const { return consumer_usage; }
-
-  gralloc1_producer_usage_t GetProducerUsage() const { return producer_usage; }
+  uint64_t GetUsage() const { return usage; }
 
   uint64_t GetBackingstore() const { return id; }
 };
diff --git a/libgralloc1/gr_utils.cpp b/gralloc/gr_utils.cpp
similarity index 88%
rename from libgralloc1/gr_utils.cpp
rename to gralloc/gr_utils.cpp
index 480ad98..68bdb4c 100644
--- a/libgralloc1/gr_utils.cpp
+++ b/gralloc/gr_utils.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2018, The Linux Foundation. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -30,8 +30,8 @@
 #include <media/msm_media_info.h>
 #include <algorithm>
 
-#include "gr_utils.h"
 #include "gr_adreno_info.h"
+#include "gr_utils.h"
 #include "qdMetaData.h"
 
 #define ASTC_BLOCK_SIZE 16
@@ -40,14 +40,14 @@
 #define COLOR_FMT_P010_UBWC 9
 #endif
 
-namespace gralloc1 {
+namespace gralloc {
 
 bool IsYuvFormat(const private_handle_t *hnd) {
   switch (hnd->format) {
     case HAL_PIXEL_FORMAT_YCbCr_420_SP:
     case HAL_PIXEL_FORMAT_YCbCr_422_SP:
     case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS:
-    case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:   // Same as YCbCr_420_SP_VENUS
+    case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:  // Same as YCbCr_420_SP_VENUS
     case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC:
     case HAL_PIXEL_FORMAT_YCrCb_420_SP:
     case HAL_PIXEL_FORMAT_YCrCb_422_SP:
@@ -177,24 +177,20 @@
   return bpp;
 }
 
-bool CpuCanAccess(gralloc1_producer_usage_t prod_usage, gralloc1_consumer_usage_t cons_usage) {
-  return CpuCanRead(prod_usage, cons_usage) || CpuCanWrite(prod_usage);
+bool CpuCanAccess(uint64_t usage) {
+  return CpuCanRead(usage) || CpuCanWrite(usage);
 }
 
-bool CpuCanRead(gralloc1_producer_usage_t prod_usage, gralloc1_consumer_usage_t cons_usage) {
-  if (prod_usage & GRALLOC1_PRODUCER_USAGE_CPU_READ) {
-    return true;
-  }
-
-  if (cons_usage & GRALLOC1_CONSUMER_USAGE_CPU_READ) {
+bool CpuCanRead(uint64_t usage) {
+  if (usage & BufferUsage::CPU_READ_MASK) {
     return true;
   }
 
   return false;
 }
 
-bool CpuCanWrite(gralloc1_producer_usage_t prod_usage) {
-  if (prod_usage & GRALLOC1_PRODUCER_USAGE_CPU_WRITE) {
+bool CpuCanWrite(uint64_t usage) {
+  if (usage & BufferUsage::CPU_WRITE_MASK) {
     // Application intends to use CPU for rendering
     return true;
   }
@@ -202,16 +198,14 @@
   return false;
 }
 
-unsigned int GetSize(const BufferInfo &info, unsigned int alignedw,
-                     unsigned int alignedh) {
+unsigned int GetSize(const BufferInfo &info, unsigned int alignedw, unsigned int alignedh) {
   unsigned int size = 0;
   int format = info.format;
   int width = info.width;
   int height = info.height;
-  gralloc1_producer_usage_t prod_usage = info.prod_usage;
-  gralloc1_consumer_usage_t cons_usage = info.cons_usage;
+  uint64_t usage = info.usage;
 
-  if (IsUBwcEnabled(format, prod_usage, cons_usage)) {
+  if (IsUBwcEnabled(format, usage)) {
     return GetUBwcSize(width, height, format, alignedw, alignedh);
   }
 
@@ -308,14 +302,14 @@
   return size;
 }
 
-void GetBufferSizeAndDimensions(const BufferInfo &info, unsigned int *size,
-                                unsigned int *alignedw, unsigned int *alignedh) {
+void GetBufferSizeAndDimensions(const BufferInfo &info, unsigned int *size, unsigned int *alignedw,
+                                unsigned int *alignedh) {
   GetAlignedWidthAndHeight(info, alignedw, alignedh);
   *size = GetSize(info, *alignedw, *alignedh);
 }
 
-void GetYuvUbwcSPPlaneInfo(uint64_t base, uint32_t width, uint32_t height,
-                           int color_format, struct android_ycbcr *ycbcr) {
+void GetYuvUbwcSPPlaneInfo(uint64_t base, uint32_t width, uint32_t height, int color_format,
+                           struct android_ycbcr *ycbcr) {
   // UBWC buffer has these 4 planes in the following sequence:
   // Y_Meta_Plane, Y_Plane, UV_Meta_Plane, UV_Plane
   unsigned int y_meta_stride, y_meta_height, y_meta_size;
@@ -383,8 +377,7 @@
   uint32_t width = UINT(hnd->width);
   uint32_t height = UINT(hnd->height);
   int format = hnd->format;
-  gralloc1_producer_usage_t prod_usage = hnd->GetProducerUsage();
-  gralloc1_consumer_usage_t cons_usage = hnd->GetConsumerUsage();
+  uint64_t usage = hnd->usage;
   unsigned int ystride, cstride;
   bool interlaced = false;
 
@@ -392,29 +385,21 @@
 
   // Check if UBWC buffer has been rendered in linear format.
   int linear_format = 0;
-  if (getMetaData(const_cast<private_handle_t *>(hnd),
-                  GET_LINEAR_FORMAT, &linear_format) == 0) {
-      format = INT(linear_format);
+  if (getMetaData(const_cast<private_handle_t *>(hnd), GET_LINEAR_FORMAT, &linear_format) == 0) {
+    format = INT(linear_format);
   }
 
   // Check metadata if the geometry has been updated.
   BufferDim_t buffer_dim;
-  if (getMetaData(const_cast<private_handle_t *>(hnd),
-                  GET_BUFFER_GEOMETRY, &buffer_dim) == 0) {
-    int usage = 0;
-    if (hnd->flags & private_handle_t::PRIV_FLAGS_UBWC_ALIGNED) {
-      usage = GRALLOC1_PRODUCER_USAGE_PRIVATE_ALLOC_UBWC;
-    }
-
-    BufferInfo info(buffer_dim.sliceWidth, buffer_dim.sliceHeight, format,
-                    prod_usage, cons_usage);
+  if (getMetaData(const_cast<private_handle_t *>(hnd), GET_BUFFER_GEOMETRY, &buffer_dim) == 0) {
+    BufferInfo info(buffer_dim.sliceWidth, buffer_dim.sliceHeight, format, usage);
     GetAlignedWidthAndHeight(info, &width, &height);
   }
 
   // Check metadata for interlaced content.
   int interlace_flag = 0;
-  if (getMetaData(const_cast<private_handle_t *>(hnd),
-                  GET_PP_PARAM_INTERLACED, &interlace_flag) == 0) {
+  if (getMetaData(const_cast<private_handle_t *>(hnd), GET_PP_PARAM_INTERLACED, &interlace_flag) ==
+      0) {
     interlaced = interlace_flag;
   }
 
@@ -457,8 +442,8 @@
       ystride = VENUS_Y_STRIDE(COLOR_FMT_P010, width);
       cstride = VENUS_UV_STRIDE(COLOR_FMT_P010, width);
       ycbcr->y = reinterpret_cast<void *>(hnd->base);
-      ycbcr->cb = reinterpret_cast<void *>(hnd->base +
-                                           ystride * VENUS_Y_SCANLINES(COLOR_FMT_P010, height));
+      ycbcr->cb =
+          reinterpret_cast<void *>(hnd->base + ystride * VENUS_Y_SCANLINES(COLOR_FMT_P010, height));
       ycbcr->cr = reinterpret_cast<void *>(hnd->base +
                                            ystride * VENUS_Y_SCANLINES(COLOR_FMT_P010, height) + 1);
       ycbcr->ystride = ystride;
@@ -494,7 +479,7 @@
     case HAL_PIXEL_FORMAT_CbYCrY_422_I:
       ystride = width * 2;
       cstride = 0;
-      ycbcr->y  = reinterpret_cast<void *>(hnd->base);
+      ycbcr->y = reinterpret_cast<void *>(hnd->base);
       ycbcr->cr = NULL;
       ycbcr->cb = NULL;
       ycbcr->ystride = ystride;
@@ -543,8 +528,7 @@
   return false;
 }
 
-bool IsUBwcEnabled(int format, gralloc1_producer_usage_t prod_usage,
-                   gralloc1_consumer_usage_t cons_usage) {
+bool IsUBwcEnabled(int format, uint64_t usage) {
   // Allow UBWC, if client is using an explicitly defined UBWC pixel format.
   if (IsUBwcFormat(format)) {
     return true;
@@ -553,18 +537,17 @@
   // Allow UBWC, if an OpenGL client sets UBWC usage flag and GPU plus MDP
   // support the format. OR if a non-OpenGL client like Rotator, sets UBWC
   // usage flag and MDP supports the format.
-  if ((prod_usage & GRALLOC1_PRODUCER_USAGE_PRIVATE_ALLOC_UBWC) && IsUBwcSupported(format)) {
+  if ((usage & GRALLOC_USAGE_PRIVATE_ALLOC_UBWC) && IsUBwcSupported(format)) {
     bool enable = true;
     // Query GPU for UBWC only if buffer is intended to be used by GPU.
-    if ((cons_usage & GRALLOC1_CONSUMER_USAGE_GPU_TEXTURE) ||
-        (prod_usage & GRALLOC1_PRODUCER_USAGE_GPU_RENDER_TARGET)) {
+    if ((usage & BufferUsage::GPU_TEXTURE) || (usage & BufferUsage::GPU_RENDER_TARGET)) {
       if (AdrenoMemInfo::GetInstance()) {
         enable = AdrenoMemInfo::GetInstance()->IsUBWCSupportedByGPU(format);
       }
     }
 
     // Allow UBWC, only if CPU usage flags are not set
-    if (enable && !(CpuCanAccess(prod_usage, cons_usage))) {
+    if (enable && !(CpuCanAccess(usage))) {
       return true;
     }
   }
@@ -683,7 +666,7 @@
   int err = 0;
 
   // This api is for RGB* formats
-  if (!gralloc1::IsUncompressedRGBFormat(hnd->format)) {
+  if (!IsUncompressedRGBFormat(hnd->format)) {
     return -EINVAL;
   }
 
@@ -713,16 +696,60 @@
   return err;
 }
 
+void GetCustomDimensions(private_handle_t *hnd, int *stride, int *height) {
+  BufferDim_t buffer_dim;
+  int interlaced = 0;
+
+  *stride = hnd->width;
+  *height = hnd->height;
+  if (getMetaData(hnd, GET_BUFFER_GEOMETRY, &buffer_dim) == 0) {
+    *stride = buffer_dim.sliceWidth;
+    *height = buffer_dim.sliceHeight;
+  } else if (getMetaData(hnd, GET_PP_PARAM_INTERLACED, &interlaced) == 0) {
+    if (interlaced && IsUBwcFormat(hnd->format)) {
+      unsigned int alignedw = 0, alignedh = 0;
+      // Get re-aligned height for single ubwc interlaced field and
+      // multiply by 2 to get frame height.
+      BufferInfo info(hnd->width, ((hnd->height + 1) >> 1), hnd->format);
+      GetAlignedWidthAndHeight(info, &alignedw, &alignedh);
+      *stride = static_cast<int>(alignedw);
+      *height = static_cast<int>(alignedh * 2);
+    }
+  }
+}
+
+void GetColorSpaceFromMetadata(private_handle_t *hnd, int *color_space) {
+  ColorMetaData color_metadata;
+  if (getMetaData(hnd, GET_COLOR_METADATA, &color_metadata) == 0) {
+    switch (color_metadata.colorPrimaries) {
+      case ColorPrimaries_BT709_5:
+        *color_space = HAL_CSC_ITU_R_709;
+        break;
+      case ColorPrimaries_BT601_6_525:
+      case ColorPrimaries_BT601_6_625:
+        *color_space = ((color_metadata.range) ? HAL_CSC_ITU_R_601_FR : HAL_CSC_ITU_R_601);
+        break;
+      case ColorPrimaries_BT2020:
+        *color_space = (color_metadata.range) ? HAL_CSC_ITU_R_2020_FR : HAL_CSC_ITU_R_2020;
+        break;
+      default:
+        ALOGE("Unknown Color Space = %d", color_metadata.colorPrimaries);
+        break;
+    }
+  } else if (getMetaData(hnd, GET_COLOR_SPACE, color_space) != 0) {
+    *color_space = 0;
+  }
+}
+
 void GetAlignedWidthAndHeight(const BufferInfo &info, unsigned int *alignedw,
                               unsigned int *alignedh) {
   int width = info.width;
   int height = info.height;
   int format = info.format;
-  gralloc1_producer_usage_t prod_usage = info.prod_usage;
-  gralloc1_consumer_usage_t cons_usage = info.cons_usage;
+  uint64_t usage = info.usage;
 
   // Currently surface padding is only computed for RGB* surfaces.
-  bool ubwc_enabled = IsUBwcEnabled(format, prod_usage, cons_usage);
+  bool ubwc_enabled = IsUBwcEnabled(format, usage);
   int tile = ubwc_enabled;
 
   if (IsUncompressedRGBFormat(format)) {
@@ -815,8 +842,8 @@
   *alignedh = (unsigned int)aligned_h;
 }
 
-int GetBufferLayout(private_handle_t *hnd, uint32_t stride[4],
-                    uint32_t offset[4], uint32_t *num_planes) {
+int GetBufferLayout(private_handle_t *hnd, uint32_t stride[4], uint32_t offset[4],
+                    uint32_t *num_planes) {
   if (!hnd || !stride || !offset || !num_planes) {
     return -EINVAL;
   }
@@ -903,4 +930,4 @@
   return 0;
 }
 
-}  // namespace gralloc1
+}  // namespace gralloc
diff --git a/libgralloc1/gr_utils.h b/gralloc/gr_utils.h
similarity index 77%
rename from libgralloc1/gr_utils.h
rename to gralloc/gr_utils.h
index 7fcb6c2..eb35a6a 100644
--- a/libgralloc1/gr_utils.h
+++ b/gralloc/gr_utils.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2016, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2016,2018, The Linux Foundation. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -30,6 +30,7 @@
 #ifndef __GR_UTILS_H__
 #define __GR_UTILS_H__
 
+#include <android/hardware/graphics/common/1.0/types.h>
 #include "gralloc_priv.h"
 
 #define SZ_2M 0x200000
@@ -42,17 +43,16 @@
 #define INT(exp) static_cast<int>(exp)
 #define UINT(exp) static_cast<unsigned int>(exp)
 
-namespace gralloc1 {
+using android::hardware::graphics::common::V1_0::BufferUsage;
 
+namespace gralloc {
 struct BufferInfo {
-  BufferInfo(int w, int h, int f, gralloc1_producer_usage_t prod = GRALLOC1_PRODUCER_USAGE_NONE,
-             gralloc1_consumer_usage_t cons = GRALLOC1_CONSUMER_USAGE_NONE) : width(w), height(h),
-    format(f), prod_usage(prod), cons_usage(cons) {}
+  BufferInfo(int w, int h, int f, uint64_t usage = 0)
+      : width(w), height(h), format(f), usage(usage) {}
   int width;
   int height;
   int format;
-  gralloc1_producer_usage_t prod_usage;
-  gralloc1_consumer_usage_t cons_usage;
+  uint64_t usage;
 };
 
 template <class Type1, class Type2>
@@ -64,20 +64,21 @@
 bool IsCompressedRGBFormat(int format);
 bool IsUncompressedRGBFormat(int format);
 uint32_t GetBppForUncompressedRGB(int format);
-bool CpuCanAccess(gralloc1_producer_usage_t prod_usage, gralloc1_consumer_usage_t cons_usage);
-bool CpuCanRead(gralloc1_producer_usage_t prod_usage, gralloc1_consumer_usage_t cons_usage);
-bool CpuCanWrite(gralloc1_producer_usage_t prod_usage);
+bool CpuCanAccess(uint64_t usage);
+bool CpuCanRead(uint64_t usage);
+bool CpuCanWrite(uint64_t usage);
 unsigned int GetSize(const BufferInfo &d, unsigned int alignedw, unsigned int alignedh);
-void GetBufferSizeAndDimensions(const BufferInfo &d, unsigned int *size,
-                                unsigned int *alignedw, unsigned int *alignedh);
+void GetBufferSizeAndDimensions(const BufferInfo &d, unsigned int *size, unsigned int *alignedw,
+                                unsigned int *alignedh);
+void GetCustomDimensions(private_handle_t *hnd, int *stride, int *height);
+void GetColorSpaceFromMetadata(private_handle_t *hnd, int *color_space);
 void GetAlignedWidthAndHeight(const BufferInfo &d, unsigned int *aligned_w,
                               unsigned int *aligned_h);
 int GetYUVPlaneInfo(const private_handle_t *hnd, struct android_ycbcr ycbcr[2]);
 int GetRgbDataAddress(private_handle_t *hnd, void **rgb_data);
 bool IsUBwcFormat(int format);
 bool IsUBwcSupported(int format);
-bool IsUBwcEnabled(int format, gralloc1_producer_usage_t prod_usage,
-                   gralloc1_consumer_usage_t cons_usage);
+bool IsUBwcEnabled(int format, uint64_t usage);
 void GetYuvUBwcWidthAndHeight(int width, int height, int format, unsigned int *aligned_w,
                               unsigned int *aligned_h);
 void GetYuvSPPlaneInfo(uint64_t base, uint32_t width, uint32_t height, uint32_t bpp,
@@ -90,8 +91,9 @@
 unsigned int GetRgbUBwcMetaBufferSize(int width, int height, uint32_t bpp);
 unsigned int GetUBwcSize(int width, int height, int format, unsigned int alignedw,
                          unsigned int alignedh);
-int GetBufferLayout(private_handle_t *hnd, uint32_t stride[4],
-                    uint32_t offset[4], uint32_t *num_planes);
-}  // namespace gralloc1
+int GetBufferLayout(private_handle_t *hnd, uint32_t stride[4], uint32_t offset[4],
+                    uint32_t *num_planes);
+
+}  // namespace gralloc
 
 #endif  // __GR_UTILS_H__
diff --git a/libgralloc1/gralloc_priv.h b/gralloc/gralloc_priv.h
similarity index 71%
rename from libgralloc1/gralloc_priv.h
rename to gralloc/gralloc_priv.h
index fb50965..c6e8ca6 100644
--- a/libgralloc1/gralloc_priv.h
+++ b/gralloc/gralloc_priv.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2018, The Linux Foundation. All rights reserved.
  * Not a Contribution
  *
  * Copyright (C) 2008 The Android Open Source Project
@@ -26,66 +26,49 @@
 
 #define ROUND_UP_PAGESIZE(x) roundUpToPageSize(x)
 inline int roundUpToPageSize(int x) {
-    return (x + (getpagesize()-1)) & ~(getpagesize()-1);
+  return (x + (getpagesize() - 1)) & ~(getpagesize() - 1);
 }
 
 /* Gralloc usage bits indicating the type of allocation that should be used */
-/* Refer gralloc1_producer_usage_t & gralloc1_consumer_usage-t in gralloc1.h */
+/* Refer to BufferUsage in hardware/interfaces/graphics/common/<ver>/types.hal */
 
-/* Producer flags */
+/* The bits below are in officially defined vendor space
+ * i.e bits 28-31 and 48-63*/
 /* Non linear, Universal Bandwidth Compression */
-#define GRALLOC1_PRODUCER_USAGE_PRIVATE_ALLOC_UBWC  GRALLOC1_PRODUCER_USAGE_PRIVATE_0
+#define GRALLOC_USAGE_PRIVATE_ALLOC_UBWC 1 << 28
 
 /* Set this for allocating uncached memory (using O_DSYNC),
  * cannot be used with noncontiguous heaps */
-#define GRALLOC1_PRODUCER_USAGE_PRIVATE_UNCACHED    GRALLOC1_PRODUCER_USAGE_PRIVATE_1
+#define GRALLOC_USAGE_PRIVATE_UNCACHED 1 << 29
 
 /* This flag is used to indicate P010 format */
-#define GRALLOC1_PRODUCER_USAGE_PRIVATE_10BIT       GRALLOC1_PRODUCER_USAGE_PRIVATE_2
-
-/* ADSP heap is a carveout heap, is not secured */
-#define GRALLOC1_PRODUCER_USAGE_PRIVATE_ADSP_HEAP   GRALLOC1_PRODUCER_USAGE_PRIVATE_3
-
-/* IOMMU heap comes from manually allocated pages, can be cached/uncached, is not secured */
-#define GRALLOC1_PRODUCER_USAGE_PRIVATE_IOMMU_HEAP  GRALLOC1_PRODUCER_USAGE_PRIVATE_4
-
-/* MM heap is a carveout heap for video, can be secured */
-#define GRALLOC1_PRODUCER_USAGE_PRIVATE_MM_HEAP     GRALLOC1_PRODUCER_USAGE_PRIVATE_5
-
-/* Use legacy ZSL definition until we know the correct usage on gralloc1 */
-#define GRALLOC1_PRODUCER_USAGE_PRIVATE_CAMERA_ZSL  GRALLOC_USAGE_HW_CAMERA_ZSL
-
-/* TODO(user): move these to use producer private bits once 64-bit support available */
-/* This flag is used to indicate 10-bit tight pack format (e.g. TP10) */
-#define GRALLOC1_PRODUCER_USAGE_PRIVATE_10BIT_TP  0x08000000
-#define GRALLOC1_CONSUMER_USAGE_PRIVATE_10BIT_TP  0x08000000
-
-
-/* Consumer flags */
-/* TODO(user): Fix when producer and consumer flags are actually separated */
-/* This flag is set for WFD usecase */
-#define GRALLOC1_CONSUMER_USAGE_PRIVATE_WFD            0x00200000
+#define GRALLOC_USAGE_PRIVATE_10BIT 1 << 30
 
 /* This flag is used for SECURE display usecase */
-#define GRALLOC1_CONSUMER_USAGE_PRIVATE_SECURE_DISPLAY 0x01000000
+#define GRALLOC_USAGE_PRIVATE_SECURE_DISPLAY 1 << 31
 
-/* This flag is used to indicate P010 format */
-#define GRALLOC1_CONSUMER_USAGE_PRIVATE_10BIT       GRALLOC1_PRODUCER_USAGE_PRIVATE_10BIT
+/* unused legacy flags */
+#define GRALLOC_USAGE_PRIVATE_MM_HEAP 0
+#define GRALLOC_USAGE_PRIVATE_IOMMU_HEAP 0
 
-/* Unused flag */
-#define GRALLOC1_USAGE_PRIVATE_UNUSED1  0x04000000
+/* TODO(user): move these to use sanctioned vendor bits
+ * once end to end 64-bit support is available */
+/* This flag is set for WFD usecase */
+#define GRALLOC_USAGE_PRIVATE_WFD 1 << 21
 
+/* This flag is used to indicate 10-bit tight pack format (e.g. TP10) */
+#define GRALLOC_USAGE_PRIVATE_10BIT_TP 1 << 27
 
-/* Legacy gralloc0.x definitions */
+/* Legacy gralloc1 definitions */
 /* Some clients may still be using the old flags */
-#define GRALLOC_USAGE_PRIVATE_ALLOC_UBWC GRALLOC1_PRODUCER_USAGE_PRIVATE_ALLOC_UBWC
-#define GRALLOC_USAGE_PRIVATE_UNCACHED GRALLOC1_PRODUCER_USAGE_PRIVATE_UNCACHED
-#define GRALLOC_USAGE_PRIVATE_IOMMU_HEAP GRALLOC1_PRODUCER_USAGE_PRIVATE_IOMMU_HEAP
-#define GRALLOC_USAGE_PRIVATE_WFD GRALLOC1_CONSUMER_USAGE_PRIVATE_WFD
-#define GRALLOC_USAGE_PRIVATE_SECURE_DISPLAY GRALLOC1_CONSUMER_USAGE_PRIVATE_SECURE_DISPLAY
-#define GRALLOC_USAGE_PRIVATE_MM_HEAP 0x0
-
-
+#define GRALLOC1_PRODUCER_USAGE_PRIVATE_ADSP_HEAP GRALLOC_USAGE_PRIVATE_ADSP_HEAP
+#define GRALLOC1_PRODUCER_USAGE_PRIVATE_ALLOC_UBWC GRALLOC_USAGE_PRIVATE_ALLOC_UBWC
+#define GRALLOC1_PRODUCER_USAGE_PRIVATE_UNCACHED GRALLOC_USAGE_PRIVATE_UNCACHED
+#define GRALLOC1_CONSUMER_USAGE_PRIVATE_SECURE_DISPLAY GRALLOC_USAGE_PRIVATE_SECURE_DISPLAY
+#define GRALLOC1_PRODUCER_USAGE_PRIVATE_MM_HEAP GRALLOC_USAGE_PRIVATE_MM_HEAP
+#define GRALLOC1_PRODUCER_USAGE_PRIVATE_10BIT GRALLOC_USAGE_PRIVATE_10BIT
+#define GRALLOC1_PRODUCER_USAGE_PRIVATE_10BIT_TP GRALLOC_USAGE_PRIVATE_10BIT_TP
+#define GRALLOC1_CONSUMER_USAGE_PRIVATE_10BIT_TP GRALLOC_USAGE_PRIVATE_10BIT_TP
 
 // for PERFORM API :
 #define GRALLOC_MODULE_PERFORM_CREATE_HANDLE_FROM_BUFFER 1
@@ -136,8 +119,8 @@
 #define HAL_PIXEL_FORMAT_YCbCr_420_P010_UBWC 0x124
 #define HAL_PIXEL_FORMAT_YCbCr_420_P010_VENUS 0x7FA30C0A
 
-#define HAL_PIXEL_FORMAT_CbYCrY_422_I            0x120
-#define HAL_PIXEL_FORMAT_BGR_888                 0x121
+#define HAL_PIXEL_FORMAT_CbYCrY_422_I 0x120
+#define HAL_PIXEL_FORMAT_BGR_888 0x121
 
 #define HAL_PIXEL_FORMAT_INTERLACE 0x180
 
@@ -150,7 +133,7 @@
 
 // UBWC aligned Venus format
 #define HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC 0x7FA30C06
-#define HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC     0x7FA30C09
+#define HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC 0x7FA30C09
 
 // Khronos ASTC formats
 #define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93B0
@@ -187,11 +170,11 @@
 #define HAL_IGC_s_RGB 1
 
 /* Color Space: Values maps to ColorSpace_t in qdMetadata.h */
-#define HAL_CSC_ITU_R_601         0
-#define HAL_CSC_ITU_R_601_FR      1
-#define HAL_CSC_ITU_R_709         2
-#define HAL_CSC_ITU_R_2020        3
-#define HAL_CSC_ITU_R_2020_FR     4
+#define HAL_CSC_ITU_R_601 0
+#define HAL_CSC_ITU_R_601_FR 1
+#define HAL_CSC_ITU_R_709 2
+#define HAL_CSC_ITU_R_2020 3
+#define HAL_CSC_ITU_R_2020_FR 4
 
 /* possible formats for 3D content*/
 enum {
diff --git a/gralloc/service.cpp b/gralloc/service.cpp
new file mode 100644
index 0000000..1136e2f
--- /dev/null
+++ b/gralloc/service.cpp
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2018, The Linux Foundation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *    * Redistributions of source code must retain the above copyright
+ *      notice, this list of conditions and the following disclaimer.
+ *    * Redistributions in binary form must reproduce the above
+ *      copyright notice, this list of conditions and the following
+ *      disclaimer in the documentation and/or other materials provided
+ *      with the distribution.
+ *    * Neither the name of The Linux Foundation. nor the names of its
+ *      contributors may be used to endorse or promote products derived
+ *      from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+ * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include <binder/ProcessState.h>
+#include <hidl/LegacySupport.h>
+#include "QtiAllocator.h"
+
+using android::hardware::configureRpcThreadpool;
+using android::hardware::joinRpcThreadpool;
+using vendor::qti::hardware::display::allocator::V1_0::implementation::QtiAllocator;
+using android::hardware::graphics::allocator::V2_0::IAllocator;
+
+int main(int, char **) {
+  android::sp<IAllocator> service = new QtiAllocator();
+  configureRpcThreadpool(1, true /*callerWillJoin*/);
+  if (service->registerAsService() != android::OK) {
+    ALOGE("Cannot register QTI Allocator service");
+    return -EINVAL;
+  }
+  ALOGI("Initialized qti-allocator");
+  joinRpcThreadpool();
+  return 0;
+}
diff --git a/gralloc/vendor.qti.hardware.display.allocator@1.0-service.rc b/gralloc/vendor.qti.hardware.display.allocator@1.0-service.rc
new file mode 100644
index 0000000..07bb2ff
--- /dev/null
+++ b/gralloc/vendor.qti.hardware.display.allocator@1.0-service.rc
@@ -0,0 +1,6 @@
+service vendor.qti.hardware.display.allocator /vendor/bin/hw/vendor.qti.hardware.display.allocator@1.0-service
+    class hal animation
+    user system
+    group graphics drmrpc
+    capabilities SYS_NICE
+    onrestart restart surfaceflinger
diff --git a/hdmi_cec/qhdmi_cec.cpp b/hdmi_cec/qhdmi_cec.cpp
index 0923d92..2760334 100644
--- a/hdmi_cec/qhdmi_cec.cpp
+++ b/hdmi_cec/qhdmi_cec.cpp
@@ -30,7 +30,7 @@
 #define DEBUG 0
 #define ATRACE_TAG (ATRACE_TAG_GRAPHICS | ATRACE_TAG_HAL)
 #include <cstdlib>
-#include <cutils/log.h>
+#include <log/log.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <hardware/hdmi_cec.h>
diff --git a/include/Android.mk b/include/Android.mk
index a72d5c3..6e529cd 100644
--- a/include/Android.mk
+++ b/include/Android.mk
@@ -19,6 +19,7 @@
                                  $(display_top)/libqservice \
                                  $(display_top)/gpu_tonemapper \
                                  $(display_top)/sdm/include \
+                                 $(display_top)/gralloc \
                                  $(display_top)/libgralloc1
 
 include $(BUILD_HEADER_LIBRARY)
diff --git a/libcopybit/copybit.cpp b/libcopybit/copybit.cpp
index 80b3cfe..bd49edc 100644
--- a/libcopybit/copybit.cpp
+++ b/libcopybit/copybit.cpp
@@ -18,7 +18,7 @@
  * limitations under the License.
  */
 
-#include <cutils/log.h>
+#include <log/log.h>
 
 #include <linux/msm_mdp.h>
 #include <linux/fb.h>
diff --git a/libcopybit/copybit_c2d.cpp b/libcopybit/copybit_c2d.cpp
index 240ba26..63c1379 100644
--- a/libcopybit/copybit_c2d.cpp
+++ b/libcopybit/copybit_c2d.cpp
@@ -17,7 +17,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#include <cutils/log.h>
+#include <log/log.h>
 #include <sys/resource.h>
 #include <sys/prctl.h>
 
diff --git a/libcopybit/software_converter.cpp b/libcopybit/software_converter.cpp
index e5c03b5..1aa3ce6 100644
--- a/libcopybit/software_converter.cpp
+++ b/libcopybit/software_converter.cpp
@@ -27,7 +27,7 @@
  * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include <cutils/log.h>
+#include <log/log.h>
 #include <stdlib.h>
 #include <errno.h>
 #include "software_converter.h"
diff --git a/libdisplayconfig/Android.mk b/libdisplayconfig/Android.mk
index a107ea6..9f84c61 100644
--- a/libdisplayconfig/Android.mk
+++ b/libdisplayconfig/Android.mk
@@ -4,10 +4,9 @@
 LOCAL_MODULE                  := libdisplayconfig
 LOCAL_MODULE_TAGS             := optional
 LOCAL_HEADER_LIBRARIES        := display_headers
-LOCAL_COPY_HEADERS            := DisplayConfig.h
 LOCAL_SRC_FILES               := DisplayConfig.cpp
 LOCAL_SHARED_LIBRARIES        := libhidlbase libhidltransport libutils \
-                                 vendor.display.config@1.0 android.hidl.base@1.0
+                                 vendor.display.config@1.0
 
 ifeq ($(LLVM_SA), true)
     LOCAL_CFLAGS += --compile-and-analyze --analyzer-perf --analyzer-Werror
diff --git a/libgralloc/gralloc_priv.h b/libgralloc/gralloc_priv.h
deleted file mode 100644
index f0c6b4d..0000000
--- a/libgralloc/gralloc_priv.h
+++ /dev/null
@@ -1,347 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * Copyright (c) 2011 - 2017, The Linux Foundation. All rights reserved.
- *
- * 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 GRALLOC_PRIV_H_
-#define GRALLOC_PRIV_H_
-
-#include <stdint.h>
-#include <limits.h>
-#include <sys/cdefs.h>
-#include <hardware/gralloc.h>
-#include <pthread.h>
-#include <errno.h>
-#include <unistd.h>
-
-
-/* DEPRECATION NOTICE: This file is no longer used, please use the new
- * implementation in libgralloc1
- */
-
-
-
-
-#include <cutils/native_handle.h>
-
-#include <cutils/log.h>
-
-#define ROUND_UP_PAGESIZE(x) (unsigned int)( ((x) + getpagesize()-1)  & \
-                                             (~(getpagesize()-1)) )
-
-/* Gralloc usage bits indicating the type of allocation that should be used */
-/* SYSTEM heap comes from kernel vmalloc (ION_SYSTEM_HEAP_ID)
- * is cached by default and
- * is not secured */
-
-/* GRALLOC_USAGE_PRIVATE_0 is unused */
-
-/* Non linear, Universal Bandwidth Compression */
-#define GRALLOC_USAGE_PRIVATE_ALLOC_UBWC      GRALLOC_USAGE_PRIVATE_1
-
-/* IOMMU heap comes from manually allocated pages, can be cached/uncached,
- * is not secured */
-#define GRALLOC_USAGE_PRIVATE_IOMMU_HEAP      GRALLOC_USAGE_PRIVATE_2
-
-/* MM heap is a carveout heap for video, can be secured */
-#define GRALLOC_USAGE_PRIVATE_MM_HEAP         GRALLOC_USAGE_PRIVATE_3
-
-/* ADSP heap is a carveout heap, is not secured */
-#define GRALLOC_USAGE_PRIVATE_ADSP_HEAP       0x01000000
-
-/* Set this for allocating uncached memory (using O_DSYNC),
- * cannot be used with noncontiguous heaps */
-#define GRALLOC_USAGE_PRIVATE_UNCACHED        0x02000000
-
-/* Buffer content should be displayed on an primary display only */
-#define GRALLOC_USAGE_PRIVATE_INTERNAL_ONLY   0x04000000
-
-/* Buffer content should be displayed on an external display only */
-#define GRALLOC_USAGE_PRIVATE_EXTERNAL_ONLY   0x08000000
-
-/* This flag is set for WFD usecase */
-#define GRALLOC_USAGE_PRIVATE_WFD             0x00200000
-
-/* CAMERA heap is a carveout heap for camera, is not secured */
-#define GRALLOC_USAGE_PRIVATE_CAMERA_HEAP     0x00400000
-
-/* This flag is used for SECURE display usecase */
-#define GRALLOC_USAGE_PRIVATE_SECURE_DISPLAY  0x00800000
-
-/* define Gralloc perform */
-#define GRALLOC_MODULE_PERFORM_CREATE_HANDLE_FROM_BUFFER 1
-// This will be used by the graphics drivers to know if certain features
-// are defined in this display HAL.
-// Ex: Newer GFX libraries + Older Display HAL
-#define GRALLOC_MODULE_PERFORM_GET_STRIDE 2
-#define GRALLOC_MODULE_PERFORM_GET_CUSTOM_STRIDE_FROM_HANDLE 3
-#define GRALLOC_MODULE_PERFORM_GET_CUSTOM_STRIDE_AND_HEIGHT_FROM_HANDLE 4
-#define GRALLOC_MODULE_PERFORM_GET_ATTRIBUTES 5
-#define GRALLOC_MODULE_PERFORM_GET_COLOR_SPACE_FROM_HANDLE 6
-#define GRALLOC_MODULE_PERFORM_GET_YUV_PLANE_INFO 7
-#define GRALLOC_MODULE_PERFORM_GET_MAP_SECURE_BUFFER_INFO 8
-#define GRALLOC_MODULE_PERFORM_GET_UBWC_FLAG 9
-#define GRALLOC_MODULE_PERFORM_GET_RGB_DATA_ADDRESS 10
-#define GRALLOC_MODULE_PERFORM_GET_IGC 11
-#define GRALLOC_MODULE_PERFORM_SET_IGC 12
-#define GRALLOC_MODULE_PERFORM_SET_SINGLE_BUFFER_MODE 13
-
-/* OEM specific HAL formats */
-
-#define HAL_PIXEL_FORMAT_RGBA_5551               6
-#define HAL_PIXEL_FORMAT_RGBA_4444               7
-#define HAL_PIXEL_FORMAT_NV12_ENCODEABLE         0x102
-#define HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS      0x7FA30C04
-#define HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED      0x7FA30C03
-#define HAL_PIXEL_FORMAT_YCbCr_420_SP            0x109
-#define HAL_PIXEL_FORMAT_YCrCb_420_SP_ADRENO     0x7FA30C01
-#define HAL_PIXEL_FORMAT_YCrCb_422_SP            0x10B
-#define HAL_PIXEL_FORMAT_R_8                     0x10D
-#define HAL_PIXEL_FORMAT_RG_88                   0x10E
-#define HAL_PIXEL_FORMAT_YCbCr_444_SP            0x10F
-#define HAL_PIXEL_FORMAT_YCrCb_444_SP            0x110
-#define HAL_PIXEL_FORMAT_YCrCb_422_I             0x111
-#define HAL_PIXEL_FORMAT_BGRX_8888               0x112
-#define HAL_PIXEL_FORMAT_NV21_ZSL                0x113
-#define HAL_PIXEL_FORMAT_YCrCb_420_SP_VENUS      0x114
-#define HAL_PIXEL_FORMAT_BGR_565                 0x115
-#define HAL_PIXEL_FORMAT_RGBA_1010102            0x116
-#define HAL_PIXEL_FORMAT_ARGB_2101010            0x117
-#define HAL_PIXEL_FORMAT_RGBX_1010102            0x118
-#define HAL_PIXEL_FORMAT_XRGB_2101010            0x119
-#define HAL_PIXEL_FORMAT_BGRA_1010102            0x11A
-#define HAL_PIXEL_FORMAT_ABGR_2101010            0x11B
-#define HAL_PIXEL_FORMAT_BGRX_1010102            0x11C
-#define HAL_PIXEL_FORMAT_XBGR_2101010            0x11D
-#define HAL_PIXEL_FORMAT_YCbCr_420_P010          0x11F
-#define HAL_PIXEL_FORMAT_CbYCrY_422_I            0x120
-#define HAL_PIXEL_FORMAT_BGR_888                 0x121
-#define HAL_PIXEL_FORMAT_RAW8                    0x123
-#define HAL_PIXEL_FORMAT_YCbCr_420_P010_UBWC     0x124
-
-#define HAL_PIXEL_FORMAT_INTERLACE               0x180
-
-//v4l2_fourcc('Y', 'U', 'Y', 'L'). 24 bpp YUYV 4:2:2 10 bit per component
-#define HAL_PIXEL_FORMAT_YCbCr_422_I_10BIT       0x4C595559
-
-//v4l2_fourcc('Y', 'B', 'W', 'C'). 10 bit per component. This compressed
-//format reduces the memory access bandwidth
-#define HAL_PIXEL_FORMAT_YCbCr_422_I_10BIT_COMPRESSED  0x43574259
-
-// UBWC aligned Venus format
-#define HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC 0x7FA30C06
-#define HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC     0x7FA30C09
-
-//Khronos ASTC formats
-#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_4x4_KHR             0x93B0
-#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_5x4_KHR             0x93B1
-#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_5x5_KHR             0x93B2
-#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_6x5_KHR             0x93B3
-#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_6x6_KHR             0x93B4
-#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_8x5_KHR             0x93B5
-#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_8x6_KHR             0x93B6
-#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_8x8_KHR             0x93B7
-#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_10x5_KHR            0x93B8
-#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_10x6_KHR            0x93B9
-#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_10x8_KHR            0x93BA
-#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_10x10_KHR           0x93BB
-#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_12x10_KHR           0x93BC
-#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_12x12_KHR           0x93BD
-#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR     0x93D0
-#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR     0x93D1
-#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR     0x93D2
-#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR     0x93D3
-#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR     0x93D4
-#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR     0x93D5
-#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR     0x93D6
-#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR     0x93D7
-#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR    0x93D8
-#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR    0x93D9
-#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR    0x93DA
-#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR   0x93DB
-#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR   0x93DC
-#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR   0x93DD
-
-/* possible values for inverse gamma correction */
-#define HAL_IGC_NOT_SPECIFIED     0
-#define HAL_IGC_s_RGB             1
-
-/* Color Space: Values maps to ColorSpace_t in qdMetadata.h */
-#define HAL_CSC_ITU_R_601         0
-#define HAL_CSC_ITU_R_601_FR      1
-#define HAL_CSC_ITU_R_709         2
-#define HAL_CSC_ITU_R_2020        3
-#define HAL_CSC_ITU_R_2020_FR     4
-
-/* possible formats for 3D content*/
-enum {
-    HAL_NO_3D                      = 0x0,
-    HAL_3D_SIDE_BY_SIDE_L_R        = 0x1,
-    HAL_3D_SIDE_BY_SIDE_R_L        = 0x2,
-    HAL_3D_TOP_BOTTOM              = 0x4,
-    HAL_3D_IN_SIDE_BY_SIDE_L_R     = 0x10000, //unused legacy format
-};
-
-enum {
-    BUFFER_TYPE_UI = 0,
-    BUFFER_TYPE_VIDEO
-};
-
-#ifdef __cplusplus
-struct private_handle_t : public native_handle {
-#else
-    struct private_handle_t {
-        native_handle_t nativeHandle;
-#endif
-        enum {
-            PRIV_FLAGS_FRAMEBUFFER        = 0x00000001,
-            PRIV_FLAGS_USES_ION           = 0x00000008,
-            PRIV_FLAGS_USES_ASHMEM        = 0x00000010,
-            PRIV_FLAGS_NEEDS_FLUSH        = 0x00000020,
-            PRIV_FLAGS_INTERNAL_ONLY      = 0x00000040,
-            PRIV_FLAGS_NON_CPU_WRITER     = 0x00000080,
-            PRIV_FLAGS_NONCONTIGUOUS_MEM  = 0x00000100,
-            PRIV_FLAGS_CACHED             = 0x00000200,
-            PRIV_FLAGS_SECURE_BUFFER      = 0x00000400,
-            // Display on external only
-            PRIV_FLAGS_EXTERNAL_ONLY      = 0x00002000,
-            // Set by HWC for protected non secure buffers
-            PRIV_FLAGS_PROTECTED_BUFFER   = 0x00004000,
-            PRIV_FLAGS_VIDEO_ENCODER      = 0x00010000,
-            PRIV_FLAGS_CAMERA_WRITE       = 0x00020000,
-            PRIV_FLAGS_CAMERA_READ        = 0x00040000,
-            PRIV_FLAGS_HW_COMPOSER        = 0x00080000,
-            PRIV_FLAGS_HW_TEXTURE         = 0x00100000,
-            PRIV_FLAGS_ITU_R_601          = 0x00200000, //Unused from display
-            PRIV_FLAGS_ITU_R_601_FR       = 0x00400000, //Unused from display
-            PRIV_FLAGS_ITU_R_709          = 0x00800000, //Unused from display
-            PRIV_FLAGS_SECURE_DISPLAY     = 0x01000000,
-            // Buffer is rendered in Tile Format
-            PRIV_FLAGS_TILE_RENDERED      = 0x02000000,
-            // Buffer rendered using CPU/SW renderer
-            PRIV_FLAGS_CPU_RENDERED       = 0x04000000,
-            // Buffer is allocated with UBWC alignment
-            PRIV_FLAGS_UBWC_ALIGNED       = 0x08000000,
-            // Buffer allocated will be consumed by SF/HWC
-            PRIV_FLAGS_DISP_CONSUMER      = 0x10000000
-        };
-
-        // file-descriptors
-        int     fd;
-        int     fd_metadata;          // fd for the meta-data
-        // ints
-        int     magic;
-        int     flags;
-        unsigned int  size;
-        unsigned int  offset;
-        int     bufferType;
-        uint64_t base __attribute__((aligned(8)));
-        unsigned int  offset_metadata;
-        // The gpu address mapped into the mmu.
-        uint64_t gpuaddr __attribute__((aligned(8)));
-        int     format;
-        int     width;   // holds aligned width of the actual buffer allocated
-        int     height;  // holds aligned height of the  actual buffer allocated
-        uint64_t base_metadata __attribute__((aligned(8)));
-        int unaligned_width;   // holds width client asked to allocate
-        int unaligned_height;  // holds height client asked to allocate
-
-#ifdef __cplusplus
-        static const int sNumFds = 2;
-        static inline int sNumInts() {
-            return ((sizeof(private_handle_t) - sizeof(native_handle_t)) /
-                    sizeof(int)) - sNumFds;
-        }
-        static const int sMagic = 'gmsm';
-
-        private_handle_t(int fd, unsigned int size, int flags, int bufferType,
-                int format, int width, int height) :
-            fd(fd), fd_metadata(-1), magic(sMagic),
-            flags(flags), size(size), offset(0), bufferType(bufferType),
-            base(0), offset_metadata(0), gpuaddr(0),
-            format(format), width(width), height(height),
-            base_metadata(0), unaligned_width(width),
-            unaligned_height(height)
-        {
-            version = (int) sizeof(native_handle);
-            numInts = sNumInts();
-            numFds = sNumFds;
-        }
-
-        private_handle_t(int fd, unsigned int size, int flags, int bufferType,
-                int format, int width, int height,
-                int eFd, unsigned int eOffset, uint64_t eBase) :
-            private_handle_t(fd, size, flags, bufferType, format, width, height)
-        {
-            fd_metadata = eFd;
-            offset_metadata = eOffset;
-            base_metadata = eBase;
-        }
-
-        private_handle_t(int fd, unsigned int size, int flags, int bufferType,
-                int format, int width, int height,
-                int eFd, unsigned int eOffset, uint64_t eBase,
-                int unaligned_w, int unaligned_h) :
-            private_handle_t(fd, size, flags, bufferType, format, width, height,
-                    eFd, eOffset, eBase)
-        {
-            unaligned_width = unaligned_w;
-            unaligned_height = unaligned_h;
-        }
-
-        ~private_handle_t() {
-            magic = 0;
-        }
-
-        static int validate(const native_handle* h) {
-            const private_handle_t* hnd = (const private_handle_t*)h;
-            if (!h || h->version != sizeof(native_handle) ||
-                h->numInts != sNumInts() || h->numFds != sNumFds ||
-                hnd->magic != sMagic)
-            {
-                ALOGD("Invalid gralloc handle (at %p): "
-                      "ver(%d/%zu) ints(%d/%d) fds(%d/%d)"
-                      "magic(%c%c%c%c/%c%c%c%c)",
-                      h,
-                      h ? h->version : -1, sizeof(native_handle),
-                      h ? h->numInts : -1, sNumInts(),
-                      h ? h->numFds : -1, sNumFds,
-                      hnd ? (((hnd->magic >> 24) & 0xFF)?
-                             ((hnd->magic >> 24) & 0xFF) : '-') : '?',
-                      hnd ? (((hnd->magic >> 16) & 0xFF)?
-                             ((hnd->magic >> 16) & 0xFF) : '-') : '?',
-                      hnd ? (((hnd->magic >> 8) & 0xFF)?
-                             ((hnd->magic >> 8) & 0xFF) : '-') : '?',
-                      hnd ? (((hnd->magic >> 0) & 0xFF)?
-                             ((hnd->magic >> 0) & 0xFF) : '-') : '?',
-                      (sMagic >> 24) & 0xFF,
-                      (sMagic >> 16) & 0xFF,
-                      (sMagic >> 8) & 0xFF,
-                      (sMagic >> 0) & 0xFF);
-                return -EINVAL;
-            }
-            return 0;
-        }
-
-        static private_handle_t* dynamicCast(const native_handle* in) {
-            if (validate(in) == 0) {
-                return (private_handle_t*) in;
-            }
-            return NULL;
-        }
-#endif
-    };
-
-#endif /* GRALLOC_PRIV_H_ */
diff --git a/libgralloc1/Android.mk b/libgralloc1/Android.mk
deleted file mode 100644
index cdb651c..0000000
--- a/libgralloc1/Android.mk
+++ /dev/null
@@ -1,38 +0,0 @@
-# Gralloc module
-LOCAL_PATH := $(call my-dir)
-include $(LOCAL_PATH)/../common.mk
-include $(CLEAR_VARS)
-
-LOCAL_MODULE                  := gralloc.$(TARGET_BOARD_PLATFORM)
-LOCAL_VENDOR_MODULE           := true
-LOCAL_MODULE_RELATIVE_PATH    := hw
-LOCAL_MODULE_TAGS             := optional
-LOCAL_C_INCLUDES              := $(common_includes) \
-                                 external/libcxx/include/
-
-LOCAL_HEADER_LIBRARIES        := display_headers
-LOCAL_SHARED_LIBRARIES        := $(common_libs) libqdMetaData libsync libgrallocutils
-LOCAL_CFLAGS                  := $(common_flags) -DLOG_TAG=\"qdgralloc\" -Wall -std=c++11 -Werror
-LOCAL_CFLAGS                  += -isystem  $(kernel_includes)
-LOCAL_CLANG                   := true
-LOCAL_ADDITIONAL_DEPENDENCIES := $(common_deps) $(kernel_deps)
-LOCAL_SRC_FILES               := gr_ion_alloc.cpp \
-                                 gr_allocator.cpp \
-                                 gr_buf_mgr.cpp \
-                                 gr_device_impl.cpp
-LOCAL_COPY_HEADERS_TO         := $(common_header_export_path)
-LOCAL_COPY_HEADERS            := gr_device_impl.h gralloc_priv.h gr_priv_handle.h
-include $(BUILD_SHARED_LIBRARY)
-
-#libgrallocutils
-include $(CLEAR_VARS)
-LOCAL_MODULE                  := libgrallocutils
-LOCAL_VENDOR_MODULE           := true
-LOCAL_MODULE_TAGS             := optional
-LOCAL_C_INCLUDES              := $(common_includes) $(kernel_includes)
-LOCAL_HEADER_LIBRARIES        := display_headers
-LOCAL_SHARED_LIBRARIES        := $(common_libs) libqdMetaData libdl
-LOCAL_CFLAGS                  := $(common_flags) -DLOG_TAG=\"grallocutils\" -Wno-sign-conversion
-LOCAL_ADDITIONAL_DEPENDENCIES := $(common_deps) $(kernel_deps)
-LOCAL_SRC_FILES               := gr_utils.cpp gr_adreno_info.cpp
-include $(BUILD_SHARED_LIBRARY)
diff --git a/libgralloc1/gr_buf_descriptor.h b/libgralloc1/gr_buf_descriptor.h
deleted file mode 100644
index c909fa4..0000000
--- a/libgralloc1/gr_buf_descriptor.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (c) 2016-2017, The Linux Foundation. All rights reserved.
-
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *   * Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- *   * Redistributions in binary form must reproduce the above
- *     copyright notice, this list of conditions and the following
- *     disclaimer in the documentation and/or other materials provided
- *     with the distribution.
- *   * Neither the name of The Linux Foundation nor the names of its
- *     contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
- * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
- * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
- * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __GR_BUF_DESCRIPTOR_H__
-#define __GR_BUF_DESCRIPTOR_H__
-
-#include <hardware/gralloc1.h>
-#include <atomic>
-
-namespace gralloc1 {
-class BufferDescriptor {
- public:
-  BufferDescriptor() : id_(next_id_++) {}
-
-  BufferDescriptor(int w, int h, int f)
-      : width_(w),
-        height_(h),
-        format_(f),
-        producer_usage_(GRALLOC1_PRODUCER_USAGE_NONE),
-        consumer_usage_(GRALLOC1_CONSUMER_USAGE_NONE),
-        id_(next_id_++) {}
-
-  BufferDescriptor(int w, int h, int f, gralloc1_producer_usage_t prod_usage,
-                   gralloc1_consumer_usage_t cons_usage)
-      : width_(w),
-        height_(h),
-        format_(f),
-        producer_usage_(prod_usage),
-        consumer_usage_(cons_usage),
-        id_(next_id_++) {}
-
-  void SetConsumerUsage(gralloc1_consumer_usage_t usage) { consumer_usage_ = usage; }
-
-  void SetProducerUsage(gralloc1_producer_usage_t usage) { producer_usage_ = usage; }
-
-  void SetDimensions(int w, int h) {
-    width_ = w;
-    height_ = h;
-  }
-
-  void SetColorFormat(int format) { format_ = format; }
-
-  void SetLayerCount(uint32_t layer_count) { layer_count_ = layer_count; }
-
-  gralloc1_consumer_usage_t GetConsumerUsage() const { return consumer_usage_; }
-
-  gralloc1_producer_usage_t GetProducerUsage() const { return producer_usage_; }
-
-  int GetWidth() const { return width_; }
-
-  int GetHeight() const { return height_; }
-
-  int GetFormat() const { return format_; }
-
-  uint32_t GetLayerCount() const { return layer_count_; }
-
-  gralloc1_buffer_descriptor_t GetId() const { return id_; }
-
- private:
-  int width_ = -1;
-  int height_ = -1;
-  int format_ = -1;
-  uint32_t layer_count_ = 1;
-  gralloc1_producer_usage_t producer_usage_ = GRALLOC1_PRODUCER_USAGE_NONE;
-  gralloc1_consumer_usage_t consumer_usage_ = GRALLOC1_CONSUMER_USAGE_NONE;
-  const gralloc1_buffer_descriptor_t id_;
-  static std::atomic<gralloc1_buffer_descriptor_t> next_id_;
-};
-};  // namespace gralloc1
-#endif  // __GR_BUF_DESCRIPTOR_H__
diff --git a/libgralloc1/gr_buf_mgr.cpp b/libgralloc1/gr_buf_mgr.cpp
deleted file mode 100644
index 189f19e..0000000
--- a/libgralloc1/gr_buf_mgr.cpp
+++ /dev/null
@@ -1,906 +0,0 @@
-/*
- * Copyright (c) 2011-2017 The Linux Foundation. All rights reserved.
- * Not a Contribution
- *
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define DEBUG 0
-
-#include <iomanip>
-#include <utility>
-#include <vector>
-#include <sstream>
-
-#include "qd_utils.h"
-#include "gr_priv_handle.h"
-#include "gr_buf_descriptor.h"
-#include "gr_utils.h"
-#include "gr_buf_mgr.h"
-#include "qdMetaData.h"
-
-namespace gralloc1 {
-std::atomic<gralloc1_buffer_descriptor_t> BufferDescriptor::next_id_(1);
-
-static BufferInfo GetBufferInfo(const BufferDescriptor &descriptor) {
-  return BufferInfo(descriptor.GetWidth(), descriptor.GetHeight(), descriptor.GetFormat(),
-                    descriptor.GetProducerUsage(), descriptor.GetConsumerUsage());
-}
-
-BufferManager::BufferManager() : next_id_(0) {
-  char property[PROPERTY_VALUE_MAX];
-
-  // Map framebuffer memory
-  if ((property_get("debug.gralloc.map_fb_memory", property, NULL) > 0) &&
-      (!strncmp(property, "1", PROPERTY_VALUE_MAX) ||
-       (!strncasecmp(property, "true", PROPERTY_VALUE_MAX)))) {
-    map_fb_mem_ = true;
-  }
-
-  handles_map_.clear();
-  allocator_ = new Allocator();
-  allocator_->Init();
-}
-
-
-gralloc1_error_t BufferManager::CreateBufferDescriptor(
-    gralloc1_buffer_descriptor_t *descriptor_id) {
-  std::lock_guard<std::mutex> lock(descriptor_lock_);
-  auto descriptor = std::make_shared<BufferDescriptor>();
-  descriptors_map_.emplace(descriptor->GetId(), descriptor);
-  *descriptor_id = descriptor->GetId();
-  return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t BufferManager::DestroyBufferDescriptor(
-    gralloc1_buffer_descriptor_t descriptor_id) {
-  std::lock_guard<std::mutex> lock(descriptor_lock_);
-  const auto descriptor = descriptors_map_.find(descriptor_id);
-  if (descriptor == descriptors_map_.end()) {
-    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
-  }
-  descriptors_map_.erase(descriptor);
-  return GRALLOC1_ERROR_NONE;
-}
-
-BufferManager::~BufferManager() {
-  if (allocator_) {
-    delete allocator_;
-  }
-}
-
-gralloc1_error_t BufferManager::AllocateBuffers(uint32_t num_descriptors,
-                                                const gralloc1_buffer_descriptor_t *descriptor_ids,
-                                                buffer_handle_t *out_buffers) {
-  bool shared = true;
-  gralloc1_error_t status = GRALLOC1_ERROR_NONE;
-
-  // since GRALLOC1_CAPABILITY_TEST_ALLOCATE capability is supported
-  // client can ask to test the allocation by passing NULL out_buffers
-  bool test_allocate = !out_buffers;
-
-  // Validate descriptors
-  std::lock_guard<std::mutex> descriptor_lock(descriptor_lock_);
-  std::vector<std::shared_ptr<BufferDescriptor>> descriptors;
-  for (uint32_t i = 0; i < num_descriptors; i++) {
-    const auto map_descriptor = descriptors_map_.find(descriptor_ids[i]);
-    if (map_descriptor == descriptors_map_.end()) {
-      return GRALLOC1_ERROR_BAD_DESCRIPTOR;
-    } else {
-      descriptors.push_back(map_descriptor->second);
-    }
-  }
-
-  //  Resolve implementation defined formats
-  for (auto &descriptor : descriptors) {
-    descriptor->SetColorFormat(allocator_->GetImplDefinedFormat(descriptor->GetProducerUsage(),
-                                                                descriptor->GetConsumerUsage(),
-                                                                descriptor->GetFormat()));
-  }
-
-  // Check if input descriptors can be supported AND
-  // Find out if a single buffer can be shared for all the given input descriptors
-  uint32_t i = 0;
-  ssize_t max_buf_index = -1;
-  shared = allocator_->CheckForBufferSharing(num_descriptors, descriptors, &max_buf_index);
-
-  if (test_allocate) {
-    status = shared ? GRALLOC1_ERROR_NOT_SHARED : status;
-    return status;
-  }
-
-  std::lock_guard<std::mutex> buffer_lock(buffer_lock_);
-  if (shared && (max_buf_index >= 0)) {
-    // Allocate one and duplicate/copy the handles for each descriptor
-    if (AllocateBufferLocked(*descriptors[UINT(max_buf_index)], &out_buffers[max_buf_index])) {
-      return GRALLOC1_ERROR_NO_RESOURCES;
-    }
-
-    for (i = 0; i < num_descriptors; i++) {
-      // Create new handle for a given descriptor.
-      // Current assumption is even MetaData memory would be same
-      // Need to revisit if there is a need for own metadata memory
-      if (i != UINT(max_buf_index)) {
-        CreateSharedHandle(out_buffers[max_buf_index], *descriptors[i], &out_buffers[i]);
-      }
-    }
-  } else {
-    // Buffer sharing is not feasible.
-    // Allocate separate buffer for each descriptor
-    for (i = 0; i < num_descriptors; i++) {
-      if (AllocateBufferLocked(*descriptors[i], &out_buffers[i])) {
-        return GRALLOC1_ERROR_NO_RESOURCES;
-      }
-    }
-  }
-
-  // Allocation is successful. If backstore is not shared inform the client.
-  if (!shared) {
-    return GRALLOC1_ERROR_NOT_SHARED;
-  }
-
-  return status;
-}
-
-void BufferManager::CreateSharedHandle(buffer_handle_t inbuffer, const BufferDescriptor &descriptor,
-                                       buffer_handle_t *outbuffer) {
-  // TODO(user): This path is not verified
-  private_handle_t const *input = reinterpret_cast<private_handle_t const *>(inbuffer);
-
-  // Get Buffer attributes or dimension
-  unsigned int alignedw = 0, alignedh = 0;
-  BufferInfo info = GetBufferInfo(descriptor);
-
-  GetAlignedWidthAndHeight(info, &alignedw, &alignedh);
-
-  // create new handle from input reference handle and given descriptor
-  int flags = GetHandleFlags(descriptor.GetFormat(), descriptor.GetProducerUsage(),
-                             descriptor.GetConsumerUsage());
-  int buffer_type = GetBufferType(descriptor.GetFormat());
-
-  // Duplicate the fds
-  // TODO(user): Not sure what to do for fb_id. Use duped fd and new dimensions?
-  private_handle_t *out_hnd = new private_handle_t(dup(input->fd),
-                                                   dup(input->fd_metadata),
-                                                   flags,
-                                                   INT(alignedw),
-                                                   INT(alignedh),
-                                                   descriptor.GetWidth(),
-                                                   descriptor.GetHeight(),
-                                                   descriptor.GetFormat(),
-                                                   buffer_type,
-                                                   input->size,
-                                                   descriptor.GetProducerUsage(),
-                                                   descriptor.GetConsumerUsage());
-  out_hnd->id = ++next_id_;
-  // TODO(user): Base address of shared handle and ion handles
-  RegisterHandleLocked(out_hnd, -1, -1);
-  *outbuffer = out_hnd;
-}
-
-gralloc1_error_t BufferManager::FreeBuffer(std::shared_ptr<Buffer> buf) {
-  auto hnd = buf->handle;
-  ALOGD_IF(DEBUG, "FreeBuffer handle:%p", hnd);
-
-  if (private_handle_t::validate(hnd) != 0) {
-    ALOGE("FreeBuffer: Invalid handle: %p", hnd);
-    return GRALLOC1_ERROR_BAD_HANDLE;
-  }
-
-  if (allocator_->FreeBuffer(reinterpret_cast<void *>(hnd->base), hnd->size, hnd->offset,
-                             hnd->fd, buf->ion_handle_main) != 0) {
-    return GRALLOC1_ERROR_BAD_HANDLE;
-  }
-
-  unsigned int meta_size = ALIGN((unsigned int)sizeof(MetaData_t), PAGE_SIZE);
-  if (allocator_->FreeBuffer(reinterpret_cast<void *>(hnd->base_metadata), meta_size,
-                             hnd->offset_metadata, hnd->fd_metadata, buf->ion_handle_meta) != 0) {
-    return GRALLOC1_ERROR_BAD_HANDLE;
-  }
-
-  private_handle_t * handle = const_cast<private_handle_t *>(hnd);
-  handle->fd = -1;
-  handle->fd_metadata = -1;
-  if (!(handle->flags & private_handle_t::PRIV_FLAGS_CLIENT_ALLOCATED)) {
-      delete handle;
-  }
-  return GRALLOC1_ERROR_NONE;
-}
-
-void BufferManager::RegisterHandleLocked(const private_handle_t *hnd,
-                                         int ion_handle,
-                                         int ion_handle_meta) {
-  auto buffer = std::make_shared<Buffer>(hnd, ion_handle, ion_handle_meta);
-  handles_map_.emplace(std::make_pair(hnd, buffer));
-}
-
-gralloc1_error_t BufferManager::ImportHandleLocked(private_handle_t *hnd) {
-  ALOGD_IF(DEBUG, "Importing handle:%p id: %" PRIu64, hnd, hnd->id);
-  int ion_handle = allocator_->ImportBuffer(hnd->fd);
-  if (ion_handle < 0) {
-    ALOGE("Failed to import ion buffer: hnd: %p, fd:%d, id:%" PRIu64, hnd, hnd->fd, hnd->id);
-    return GRALLOC1_ERROR_BAD_HANDLE;
-  }
-  int ion_handle_meta = allocator_->ImportBuffer(hnd->fd_metadata);
-  if (ion_handle_meta < 0) {
-    ALOGE("Failed to import ion metadata buffer: hnd: %p, fd:%d, id:%" PRIu64, hnd,
-          hnd->fd, hnd->id);
-    return GRALLOC1_ERROR_BAD_HANDLE;
-  }
-  // Set base pointers to NULL since the data here was received over binder
-  hnd->base = 0;
-  hnd->base_metadata = 0;
-  RegisterHandleLocked(hnd, ion_handle, ion_handle_meta);
-  return GRALLOC1_ERROR_NONE;
-}
-
-std::shared_ptr<BufferManager::Buffer>
-BufferManager::GetBufferFromHandleLocked(const private_handle_t *hnd) {
-  auto it = handles_map_.find(hnd);
-  if (it != handles_map_.end()) {
-    return it->second;
-  } else {
-    return nullptr;
-  }
-}
-
-gralloc1_error_t BufferManager::MapBuffer(private_handle_t const *handle) {
-  private_handle_t *hnd = const_cast<private_handle_t *>(handle);
-  ALOGD_IF(DEBUG, "Map buffer handle:%p id: %" PRIu64, hnd, hnd->id);
-
-  hnd->base = 0;
-  if (allocator_->MapBuffer(reinterpret_cast<void **>(&hnd->base), hnd->size, hnd->offset,
-                            hnd->fd) != 0) {
-    return GRALLOC1_ERROR_BAD_HANDLE;
-  }
-  return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t BufferManager::RetainBuffer(private_handle_t const *hnd) {
-  ALOGD_IF(DEBUG, "Retain buffer handle:%p id: %" PRIu64, hnd, hnd->id);
-  gralloc1_error_t err = GRALLOC1_ERROR_NONE;
-  std::lock_guard<std::mutex> lock(buffer_lock_);
-  auto buf = GetBufferFromHandleLocked(hnd);
-  if (buf != nullptr) {
-    buf->IncRef();
-  } else {
-    private_handle_t *handle = const_cast<private_handle_t *>(hnd);
-    err = ImportHandleLocked(handle);
-  }
-  return err;
-}
-
-gralloc1_error_t BufferManager::ReleaseBuffer(private_handle_t const *hnd) {
-  ALOGD_IF(DEBUG, "Release buffer handle:%p", hnd);
-  std::lock_guard<std::mutex> lock(buffer_lock_);
-  auto buf = GetBufferFromHandleLocked(hnd);
-  if (buf == nullptr) {
-    ALOGE("Could not find handle: %p id: %" PRIu64, hnd, hnd->id);
-    return GRALLOC1_ERROR_BAD_HANDLE;
-  } else {
-    if (buf->DecRef()) {
-      handles_map_.erase(hnd);
-      // Unmap, close ion handle and close fd
-      FreeBuffer(buf);
-    }
-  }
-  return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t BufferManager::LockBuffer(const private_handle_t *hnd,
-                                           gralloc1_producer_usage_t prod_usage,
-                                           gralloc1_consumer_usage_t cons_usage) {
-  std::lock_guard<std::mutex> lock(buffer_lock_);
-  gralloc1_error_t err = GRALLOC1_ERROR_NONE;
-  ALOGD_IF(DEBUG, "LockBuffer buffer handle:%p id: %" PRIu64, hnd, hnd->id);
-
-  // If buffer is not meant for CPU return err
-  if (!CpuCanAccess(prod_usage, cons_usage)) {
-    return GRALLOC1_ERROR_BAD_VALUE;
-  }
-
-  auto buf = GetBufferFromHandleLocked(hnd);
-  if (buf == nullptr) {
-    return GRALLOC1_ERROR_BAD_HANDLE;
-  }
-
-  if (hnd->base == 0) {
-    // we need to map for real
-    err = MapBuffer(hnd);
-  }
-
-  // Invalidate if CPU reads in software and there are non-CPU
-  // writers. No need to do this for the metadata buffer as it is
-  // only read/written in software.
-
-  // todo use handle here
-  if (!err && (hnd->flags & private_handle_t::PRIV_FLAGS_USES_ION) &&
-      (hnd->flags & private_handle_t::PRIV_FLAGS_CACHED)) {
-    if (allocator_->CleanBuffer(reinterpret_cast<void *>(hnd->base), hnd->size, hnd->offset,
-                                buf->ion_handle_main, CACHE_INVALIDATE)) {
-      return GRALLOC1_ERROR_BAD_HANDLE;
-    }
-  }
-
-  // Mark the buffer to be flushed after CPU write.
-  if (!err && CpuCanWrite(prod_usage)) {
-    private_handle_t *handle = const_cast<private_handle_t *>(hnd);
-    handle->flags |= private_handle_t::PRIV_FLAGS_NEEDS_FLUSH;
-  }
-
-  return err;
-}
-
-gralloc1_error_t BufferManager::UnlockBuffer(const private_handle_t *handle) {
-  std::lock_guard<std::mutex> lock(buffer_lock_);
-  gralloc1_error_t status = GRALLOC1_ERROR_NONE;
-
-  private_handle_t *hnd = const_cast<private_handle_t *>(handle);
-  auto buf = GetBufferFromHandleLocked(hnd);
-  if (buf == nullptr) {
-    return GRALLOC1_ERROR_BAD_HANDLE;
-  }
-
-  if (hnd->flags & private_handle_t::PRIV_FLAGS_NEEDS_FLUSH) {
-    if (allocator_->CleanBuffer(reinterpret_cast<void *>(hnd->base), hnd->size, hnd->offset,
-                                buf->ion_handle_main, CACHE_CLEAN) != 0) {
-      status = GRALLOC1_ERROR_BAD_HANDLE;
-    }
-    hnd->flags &= ~private_handle_t::PRIV_FLAGS_NEEDS_FLUSH;
-  }
-
-  return status;
-}
-
-uint32_t BufferManager::GetDataAlignment(int format, gralloc1_producer_usage_t prod_usage,
-                                    gralloc1_consumer_usage_t cons_usage) {
-  uint32_t align = UINT(getpagesize());
-  if (format == HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED) {
-    align = 8192;
-  }
-
-  if (prod_usage & GRALLOC1_PRODUCER_USAGE_PROTECTED) {
-    if ((prod_usage & GRALLOC1_PRODUCER_USAGE_CAMERA) ||
-        (cons_usage & GRALLOC1_CONSUMER_USAGE_PRIVATE_SECURE_DISPLAY)) {
-      // The alignment here reflects qsee mmu V7L/V8L requirement
-      align = SZ_2M;
-    } else {
-      align = SECURE_ALIGN;
-    }
-  }
-
-  return align;
-}
-
-int BufferManager::GetHandleFlags(int format, gralloc1_producer_usage_t prod_usage,
-                                  gralloc1_consumer_usage_t cons_usage) {
-  int flags = 0;
-  if (cons_usage & GRALLOC1_CONSUMER_USAGE_VIDEO_ENCODER) {
-    flags |= private_handle_t::PRIV_FLAGS_VIDEO_ENCODER;
-  }
-
-  if (prod_usage & GRALLOC1_PRODUCER_USAGE_CAMERA) {
-    flags |= private_handle_t::PRIV_FLAGS_CAMERA_WRITE;
-  }
-
-  if (prod_usage & GRALLOC1_CONSUMER_USAGE_CAMERA) {
-    flags |= private_handle_t::PRIV_FLAGS_CAMERA_READ;
-  }
-
-  if (cons_usage & GRALLOC1_CONSUMER_USAGE_HWCOMPOSER) {
-    flags |= private_handle_t::PRIV_FLAGS_HW_COMPOSER;
-  }
-
-  if (prod_usage & GRALLOC1_CONSUMER_USAGE_GPU_TEXTURE) {
-    flags |= private_handle_t::PRIV_FLAGS_HW_TEXTURE;
-  }
-
-  if (prod_usage & GRALLOC1_CONSUMER_USAGE_PRIVATE_SECURE_DISPLAY) {
-    flags |= private_handle_t::PRIV_FLAGS_SECURE_DISPLAY;
-  }
-
-  if (IsUBwcEnabled(format, prod_usage, cons_usage)) {
-    flags |= private_handle_t::PRIV_FLAGS_UBWC_ALIGNED;
-  }
-
-  if (prod_usage & (GRALLOC1_PRODUCER_USAGE_CPU_READ | GRALLOC1_PRODUCER_USAGE_CPU_WRITE)) {
-    flags |= private_handle_t::PRIV_FLAGS_CPU_RENDERED;
-  }
-
-  // TODO(user): is this correct???
-  if ((cons_usage &
-       (GRALLOC1_CONSUMER_USAGE_VIDEO_ENCODER | GRALLOC1_CONSUMER_USAGE_CLIENT_TARGET)) ||
-      (prod_usage & (GRALLOC1_PRODUCER_USAGE_CAMERA | GRALLOC1_PRODUCER_USAGE_GPU_RENDER_TARGET))) {
-    flags |= private_handle_t::PRIV_FLAGS_NON_CPU_WRITER;
-  }
-
-  if (cons_usage & GRALLOC1_CONSUMER_USAGE_HWCOMPOSER) {
-    flags |= private_handle_t::PRIV_FLAGS_DISP_CONSUMER;
-  }
-
-  if (!allocator_->UseUncached(prod_usage, cons_usage)) {
-    flags |= private_handle_t::PRIV_FLAGS_CACHED;
-  }
-
-  return flags;
-}
-
-int BufferManager::GetBufferType(int inputFormat) {
-  int buffer_type = BUFFER_TYPE_VIDEO;
-  if (IsUncompressedRGBFormat(inputFormat)) {
-    // RGB formats
-    buffer_type = BUFFER_TYPE_UI;
-  }
-
-  return buffer_type;
-}
-
-int BufferManager::AllocateBufferLocked(const BufferDescriptor &descriptor, buffer_handle_t *handle,
-                                        unsigned int bufferSize) {
-  if (!handle)
-    return -EINVAL;
-
-  gralloc1_producer_usage_t prod_usage = descriptor.GetProducerUsage();
-  gralloc1_consumer_usage_t cons_usage = descriptor.GetConsumerUsage();
-  int format = allocator_->GetImplDefinedFormat(prod_usage, cons_usage, descriptor.GetFormat());
-  uint32_t layer_count = descriptor.GetLayerCount();
-
-  unsigned int size;
-  unsigned int alignedw, alignedh;
-
-  int buffer_type = GetBufferType(format);
-  BufferInfo info = GetBufferInfo(descriptor);
-  GetBufferSizeAndDimensions(info, &size, &alignedw, &alignedh);
-  size = (bufferSize >= size) ? bufferSize : size;
-
-  int err = 0;
-  int flags = 0;
-  auto page_size = UINT(getpagesize());
-  AllocData data;
-  data.align = GetDataAlignment(format, prod_usage, cons_usage);
-  size = ALIGN(size, data.align) * layer_count;
-  data.size = size;
-  data.handle = (uintptr_t) handle;
-  data.uncached = allocator_->UseUncached(prod_usage, cons_usage);
-
-  // Allocate buffer memory
-  err = allocator_->AllocateMem(&data, prod_usage, cons_usage);
-  if (err) {
-    ALOGE("gralloc failed to allocate err=%s", strerror(-err));
-    return err;
-  }
-
-  // Allocate memory for MetaData
-  AllocData e_data;
-  e_data.size = ALIGN(UINT(sizeof(MetaData_t)), page_size);
-  e_data.handle = data.handle;
-  e_data.align = page_size;
-
-  err =
-      allocator_->AllocateMem(&e_data, GRALLOC1_PRODUCER_USAGE_NONE, GRALLOC1_CONSUMER_USAGE_NONE);
-  if (err) {
-    ALOGE("gralloc failed to allocate metadata error=%s", strerror(-err));
-    return err;
-  }
-
-  flags = GetHandleFlags(format, prod_usage, cons_usage);
-  flags |= data.alloc_type;
-
-  // Create handle
-  private_handle_t *hnd = new private_handle_t(data.fd,
-                                               e_data.fd,
-                                               flags,
-                                               INT(alignedw),
-                                               INT(alignedh),
-                                               descriptor.GetWidth(),
-                                               descriptor.GetHeight(),
-                                               format,
-                                               buffer_type,
-                                               data.size,
-                                               prod_usage,
-                                               cons_usage);
-
-  hnd->id = ++next_id_;
-  hnd->base = 0;
-  hnd->base_metadata = 0;
-  hnd->layer_count = layer_count;
-
-  ColorSpace_t colorSpace = ITU_R_601;
-  setMetaData(hnd, UPDATE_COLOR_SPACE, reinterpret_cast<void *>(&colorSpace));
-  *handle = hnd;
-  RegisterHandleLocked(hnd, data.ion_handle, e_data.ion_handle);
-  ALOGD_IF(DEBUG, "Allocated buffer handle: %p id: %" PRIu64, hnd, hnd->id);
-  if (DEBUG) {
-    private_handle_t::Dump(hnd);
-  }
-  return err;
-}
-
-gralloc1_error_t BufferManager::Perform(int operation, va_list args) {
-  switch (operation) {
-    case GRALLOC_MODULE_PERFORM_CREATE_HANDLE_FROM_BUFFER: {
-      int fd = va_arg(args, int);
-      unsigned int size = va_arg(args, unsigned int);
-      unsigned int offset = va_arg(args, unsigned int);
-      void *base = va_arg(args, void *);
-      int width = va_arg(args, int);
-      int height = va_arg(args, int);
-      int format = va_arg(args, int);
-
-      native_handle_t **handle = va_arg(args, native_handle_t **);
-      if (!handle) {
-        return GRALLOC1_ERROR_BAD_HANDLE;
-      }
-
-      private_handle_t *hnd = reinterpret_cast<private_handle_t *>(
-          native_handle_create(private_handle_t::kNumFds, private_handle_t::NumInts()));
-      if (hnd) {
-        unsigned int alignedw = 0, alignedh = 0;
-        hnd->magic = private_handle_t::kMagic;
-        hnd->fd = fd;
-        hnd->flags = private_handle_t::PRIV_FLAGS_USES_ION;
-        hnd->size = size;
-        hnd->offset = offset;
-        hnd->base = uint64_t(base);
-        hnd->gpuaddr = 0;
-        BufferInfo info(width, height, format);
-        GetAlignedWidthAndHeight(info, &alignedw, &alignedh);
-        hnd->unaligned_width = width;
-        hnd->unaligned_height = height;
-        hnd->width = INT(alignedw);
-        hnd->height = INT(alignedh);
-        hnd->format = format;
-        *handle = reinterpret_cast<native_handle_t *>(hnd);
-      }
-    } break;
-
-    case GRALLOC_MODULE_PERFORM_GET_STRIDE: {
-      int width = va_arg(args, int);
-      int format = va_arg(args, int);
-      int *stride = va_arg(args, int *);
-      unsigned int alignedw = 0, alignedh = 0;
-
-      if (!stride) {
-        return GRALLOC1_ERROR_BAD_VALUE;
-      }
-
-      BufferInfo info(width, width, format);
-      GetAlignedWidthAndHeight(info, &alignedw, &alignedh);
-      *stride = INT(alignedw);
-    } break;
-
-    case GRALLOC_MODULE_PERFORM_GET_CUSTOM_STRIDE_FROM_HANDLE: {
-      private_handle_t *hnd = va_arg(args, private_handle_t *);
-      int *stride = va_arg(args, int *);
-      if (private_handle_t::validate(hnd) != 0) {
-        return GRALLOC1_ERROR_BAD_HANDLE;
-      }
-
-      if (!stride) {
-        return GRALLOC1_ERROR_BAD_VALUE;
-      }
-
-      BufferDim_t buffer_dim;
-      if (getMetaData(hnd, GET_BUFFER_GEOMETRY, &buffer_dim) == 0) {
-        *stride = buffer_dim.sliceWidth;
-      } else {
-        *stride = hnd->width;
-      }
-    } break;
-
-    // TODO(user) : this alone should be sufficient, ask gfx to get rid of above
-    case GRALLOC_MODULE_PERFORM_GET_CUSTOM_STRIDE_AND_HEIGHT_FROM_HANDLE: {
-      private_handle_t *hnd = va_arg(args, private_handle_t *);
-      int *stride = va_arg(args, int *);
-      int *height = va_arg(args, int *);
-      if (private_handle_t::validate(hnd) != 0) {
-        return GRALLOC1_ERROR_BAD_HANDLE;
-      }
-
-      if (!stride || !height) {
-        return GRALLOC1_ERROR_BAD_VALUE;
-      }
-
-      BufferDim_t buffer_dim;
-      int interlaced = 0;
-
-      *stride = hnd->width;
-      *height = hnd->height;
-      if (getMetaData(hnd, GET_BUFFER_GEOMETRY, &buffer_dim) == 0) {
-        *stride = buffer_dim.sliceWidth;
-        *height = buffer_dim.sliceHeight;
-      } else if (getMetaData(hnd, GET_PP_PARAM_INTERLACED, &interlaced) == 0) {
-        if (interlaced && IsUBwcFormat(hnd->format)) {
-          unsigned int alignedw = 0, alignedh = 0;
-          // Get re-aligned height for single ubwc interlaced field and
-          // multiple by 2 to get frame height.
-          BufferInfo info(hnd->width, ((hnd->height+1)>>1), hnd->format);
-          GetAlignedWidthAndHeight(info, &alignedw, &alignedh);
-          *stride = static_cast<int>(alignedw);
-          *height = static_cast<int>(alignedh * 2);
-        }
-      }
-    } break;
-
-    case GRALLOC_MODULE_PERFORM_GET_ATTRIBUTES: {
-      // TODO(user): Usage is split now. take care of it from Gfx client.
-      // see if we can directly expect descriptor from gfx client.
-      int width = va_arg(args, int);
-      int height = va_arg(args, int);
-      int format = va_arg(args, int);
-      uint64_t producer_usage = va_arg(args, uint64_t);
-      uint64_t consumer_usage = va_arg(args, uint64_t);
-      gralloc1_producer_usage_t prod_usage = static_cast<gralloc1_producer_usage_t>(producer_usage);
-      gralloc1_consumer_usage_t cons_usage = static_cast<gralloc1_consumer_usage_t>(consumer_usage);
-
-      int *aligned_width = va_arg(args, int *);
-      int *aligned_height = va_arg(args, int *);
-      int *tile_enabled = va_arg(args, int *);
-      if (!aligned_width || !aligned_height || !tile_enabled) {
-        return GRALLOC1_ERROR_BAD_VALUE;
-      }
-
-      unsigned int alignedw, alignedh;
-      BufferInfo info(width, height, format, prod_usage, cons_usage);
-      *tile_enabled = IsUBwcEnabled(format, prod_usage, cons_usage);
-      GetAlignedWidthAndHeight(info, &alignedw, &alignedh);
-      *aligned_width = INT(alignedw);
-      *aligned_height = INT(alignedh);
-    } break;
-
-    case GRALLOC_MODULE_PERFORM_GET_COLOR_SPACE_FROM_HANDLE: {
-      private_handle_t *hnd = va_arg(args, private_handle_t *);
-      int *color_space = va_arg(args, int *);
-
-      if (private_handle_t::validate(hnd) != 0) {
-        return GRALLOC1_ERROR_BAD_HANDLE;
-      }
-
-      if (!color_space) {
-        return GRALLOC1_ERROR_BAD_VALUE;
-      }
-
-      *color_space = 0;
-#ifdef USE_COLOR_METADATA
-      ColorMetaData color_metadata;
-      if (getMetaData(hnd, GET_COLOR_METADATA, &color_metadata) == 0) {
-        switch (color_metadata.colorPrimaries) {
-          case ColorPrimaries_BT709_5:
-            *color_space = HAL_CSC_ITU_R_709;
-            break;
-          case ColorPrimaries_BT601_6_525:
-          case ColorPrimaries_BT601_6_625:
-            *color_space = ((color_metadata.range) ? HAL_CSC_ITU_R_601_FR : HAL_CSC_ITU_R_601);
-            break;
-          case ColorPrimaries_BT2020:
-            *color_space = (color_metadata.range) ? HAL_CSC_ITU_R_2020_FR : HAL_CSC_ITU_R_2020;
-            break;
-          default:
-            ALOGE("Unknown Color Space = %d", color_metadata.colorPrimaries);
-            break;
-        }
-        break;
-      } else if (getMetaData(hnd, GET_COLOR_SPACE, color_space) != 0) {
-          *color_space = 0;
-      }
-#else
-      if (getMetaData(hnd, GET_COLOR_SPACE, color_space) != 0) {
-          *color_space = 0;
-      }
-#endif
-    } break;
-    case GRALLOC_MODULE_PERFORM_GET_YUV_PLANE_INFO: {
-      private_handle_t *hnd = va_arg(args, private_handle_t *);
-      android_ycbcr *ycbcr = va_arg(args, struct android_ycbcr *);
-      if (private_handle_t::validate(hnd) != 0) {
-        return GRALLOC1_ERROR_BAD_HANDLE;
-      }
-
-      if (!ycbcr) {
-        return GRALLOC1_ERROR_BAD_VALUE;
-      }
-
-      if (GetYUVPlaneInfo(hnd, ycbcr)) {
-        return GRALLOC1_ERROR_UNDEFINED;
-      }
-    } break;
-
-    case GRALLOC_MODULE_PERFORM_GET_MAP_SECURE_BUFFER_INFO: {
-      private_handle_t *hnd = va_arg(args, private_handle_t *);
-      int *map_secure_buffer = va_arg(args, int *);
-
-      if (private_handle_t::validate(hnd) != 0) {
-        return GRALLOC1_ERROR_BAD_HANDLE;
-      }
-
-      if (!map_secure_buffer) {
-        return GRALLOC1_ERROR_BAD_VALUE;
-      }
-
-      if (getMetaData(hnd, GET_MAP_SECURE_BUFFER, map_secure_buffer) != 0) {
-        *map_secure_buffer = 0;
-      }
-    } break;
-
-    case GRALLOC_MODULE_PERFORM_GET_UBWC_FLAG: {
-      private_handle_t *hnd = va_arg(args, private_handle_t *);
-      int *flag = va_arg(args, int *);
-
-      if (private_handle_t::validate(hnd) != 0) {
-        return GRALLOC1_ERROR_BAD_HANDLE;
-      }
-
-      if (!flag) {
-        return GRALLOC1_ERROR_BAD_VALUE;
-      }
-
-      *flag = hnd->flags &private_handle_t::PRIV_FLAGS_UBWC_ALIGNED;
-      int linear_format = 0;
-      if (getMetaData(hnd, GET_LINEAR_FORMAT, &linear_format) == 0) {
-        if (linear_format) {
-         *flag = 0;
-        }
-      }
-    } break;
-
-    case GRALLOC_MODULE_PERFORM_GET_RGB_DATA_ADDRESS: {
-      private_handle_t *hnd = va_arg(args, private_handle_t *);
-      void **rgb_data = va_arg(args, void **);
-
-      if (private_handle_t::validate(hnd) != 0) {
-        return GRALLOC1_ERROR_BAD_HANDLE;
-      }
-
-      if (!rgb_data) {
-        return GRALLOC1_ERROR_BAD_VALUE;
-      }
-
-      if (GetRgbDataAddress(hnd, rgb_data)) {
-        return GRALLOC1_ERROR_UNDEFINED;
-      }
-    } break;
-
-    case GRALLOC1_MODULE_PERFORM_GET_BUFFER_SIZE_AND_DIMENSIONS: {
-      int width = va_arg(args, int);
-      int height = va_arg(args, int);
-      int format = va_arg(args, int);
-      uint64_t p_usage = va_arg(args, uint64_t);
-      uint64_t c_usage = va_arg(args, uint64_t);
-      gralloc1_producer_usage_t producer_usage = static_cast<gralloc1_producer_usage_t>(p_usage);
-      gralloc1_consumer_usage_t consumer_usage = static_cast<gralloc1_consumer_usage_t>(c_usage);
-      uint32_t *aligned_width = va_arg(args, uint32_t *);
-      uint32_t *aligned_height = va_arg(args, uint32_t *);
-      uint32_t *size = va_arg(args, uint32_t *);
-
-      if (!aligned_width || !aligned_height || !size) {
-        return GRALLOC1_ERROR_BAD_VALUE;
-      }
-
-      auto info = BufferInfo(width, height, format, producer_usage, consumer_usage);
-      GetBufferSizeAndDimensions(info, size, aligned_width, aligned_height);
-      // Align size
-      auto align = GetDataAlignment(format, producer_usage, consumer_usage);
-      *size = ALIGN(*size, align);
-    } break;
-
-    case GRALLOC1_MODULE_PERFORM_GET_INTERLACE_FLAG: {
-      private_handle_t *hnd = va_arg(args, private_handle_t *);
-      int *flag = va_arg(args, int *);
-
-      if (private_handle_t::validate(hnd) != 0) {
-        return GRALLOC1_ERROR_BAD_HANDLE;
-      }
-
-      if (!flag) {
-        return GRALLOC1_ERROR_BAD_VALUE;
-      }
-
-      if (getMetaData(hnd, GET_PP_PARAM_INTERLACED, flag) != 0) {
-        *flag = 0;
-      }
-    } break;
-
-    case GRALLOC_MODULE_PERFORM_SET_SINGLE_BUFFER_MODE: {
-      private_handle_t* hnd =  va_arg(args, private_handle_t*);
-      uint32_t *enable = va_arg(args, uint32_t*);
-      if (private_handle_t::validate(hnd) != 0) {
-        return GRALLOC1_ERROR_BAD_HANDLE;
-      }
-      if (setMetaData(hnd, SET_SINGLE_BUFFER_MODE, enable) != 0) {
-        return GRALLOC1_ERROR_UNSUPPORTED;
-      }
-    } break;
-
-    default:
-      break;
-  }
-  return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t BufferManager::GetNumFlexPlanes(const private_handle_t *hnd,
-                                                 uint32_t *out_num_planes) {
-  if (!IsYuvFormat(hnd)) {
-    return GRALLOC1_ERROR_UNSUPPORTED;
-  } else {
-    *out_num_planes = 3;
-  }
-  return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t BufferManager::GetFlexLayout(const private_handle_t *hnd,
-                                              struct android_flex_layout *layout) {
-  if (!IsYuvFormat(hnd)) {
-    return GRALLOC1_ERROR_UNSUPPORTED;
-  }
-
-  android_ycbcr yuvPlaneInfo[2];
-  int err = GetYUVPlaneInfo(hnd, yuvPlaneInfo);
-
-  if (err != 0) {
-    return GRALLOC1_ERROR_BAD_HANDLE;
-  }
-
-  layout->format = FLEX_FORMAT_YCbCr;
-  layout->num_planes = 3;
-
-  for (uint32_t i = 0; i < layout->num_planes; i++) {
-    layout->planes[i].bits_per_component = 8;
-    layout->planes[i].bits_used = 8;
-    layout->planes[i].h_increment = 1;
-    layout->planes[i].v_increment = 1;
-    layout->planes[i].h_subsampling = 2;
-    layout->planes[i].v_subsampling = 2;
-  }
-
-  // We are only returning flex layout for progressive or single field formats.
-  struct android_ycbcr ycbcr = yuvPlaneInfo[0];
-  layout->planes[0].top_left = static_cast<uint8_t *>(ycbcr.y);
-  layout->planes[0].component = FLEX_COMPONENT_Y;
-  layout->planes[0].v_increment = static_cast<int32_t>(ycbcr.ystride);
-
-  layout->planes[1].top_left = static_cast<uint8_t *>(ycbcr.cb);
-  layout->planes[1].component = FLEX_COMPONENT_Cb;
-  layout->planes[1].h_increment = static_cast<int32_t>(ycbcr.chroma_step);
-  layout->planes[1].v_increment = static_cast<int32_t>(ycbcr.cstride);
-
-  layout->planes[2].top_left = static_cast<uint8_t *>(ycbcr.cr);
-  layout->planes[2].component = FLEX_COMPONENT_Cr;
-  layout->planes[2].h_increment = static_cast<int32_t>(ycbcr.chroma_step);
-  layout->planes[2].v_increment = static_cast<int32_t>(ycbcr.cstride);
-  return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t BufferManager::Dump(std::ostringstream *os) {
-  for (auto it : handles_map_) {
-    auto buf = it.second;
-    auto hnd = buf->handle;
-    *os << "handle id: " << std::setw(4) << hnd->id;
-    *os << " fd: "       << std::setw(3) << hnd->fd;
-    *os << " fd_meta: "  << std::setw(3) << hnd->fd_metadata;
-    *os << " wxh: "      << std::setw(4) << hnd->width <<" x " << std::setw(4) <<  hnd->height;
-    *os << " uwxuh: "    << std::setw(4) << hnd->unaligned_width << " x ";
-    *os << std::setw(4)  <<  hnd->unaligned_height;
-    *os << " size: "     << std::setw(9) << hnd->size;
-    *os << std::hex << std::setfill('0');
-    *os << " priv_flags: " << "0x" << std::setw(8) << hnd->flags;
-    *os << " prod_usage: " << "0x" << std::setw(8) << hnd->producer_usage;
-    *os << " cons_usage: " << "0x" << std::setw(8) << hnd->consumer_usage;
-    // TODO(user): get format string from qdutils
-    *os << " format: "     << "0x" << std::setw(8) << hnd->format;
-    *os << std::dec  << std::setfill(' ') << std::endl;
-  }
-  return GRALLOC1_ERROR_NONE;
-}
-}  //  namespace gralloc1
diff --git a/libgralloc1/gr_buf_mgr.h b/libgralloc1/gr_buf_mgr.h
deleted file mode 100644
index e021afd..0000000
--- a/libgralloc1/gr_buf_mgr.h
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (c) 2011-2017, The Linux Foundation. All rights reserved.
- * Not a Contribution
- *
- * Copyright (C) 2008 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 __GR_BUF_MGR_H__
-#define __GR_BUF_MGR_H__
-
-#include <pthread.h>
-#include <unordered_map>
-#include <unordered_set>
-#include <utility>
-#include <mutex>
-
-#include "gralloc_priv.h"
-#include "gr_allocator.h"
-#include "gr_buf_descriptor.h"
-
-namespace gralloc1 {
-
-class BufferManager {
- public:
-  ~BufferManager();
-  gralloc1_error_t CreateBufferDescriptor(gralloc1_buffer_descriptor_t *descriptor_id);
-  gralloc1_error_t DestroyBufferDescriptor(gralloc1_buffer_descriptor_t descriptor_id);
-  gralloc1_error_t AllocateBuffers(uint32_t num_descriptors,
-                                   const gralloc1_buffer_descriptor_t *descriptor_ids,
-                                   buffer_handle_t *out_buffers);
-  gralloc1_error_t RetainBuffer(private_handle_t const *hnd);
-  gralloc1_error_t ReleaseBuffer(private_handle_t const *hnd);
-  gralloc1_error_t LockBuffer(const private_handle_t *hnd, gralloc1_producer_usage_t prod_usage,
-                              gralloc1_consumer_usage_t cons_usage);
-  gralloc1_error_t UnlockBuffer(const private_handle_t *hnd);
-  gralloc1_error_t Perform(int operation, va_list args);
-  gralloc1_error_t GetFlexLayout(const private_handle_t *hnd, struct android_flex_layout *layout);
-  gralloc1_error_t GetNumFlexPlanes(const private_handle_t *hnd, uint32_t *out_num_planes);
-  gralloc1_error_t Dump(std::ostringstream *os);
-
-  template <typename... Args>
-  gralloc1_error_t CallBufferDescriptorFunction(gralloc1_buffer_descriptor_t descriptor_id,
-                                                void (BufferDescriptor::*member)(Args...),
-                                                Args... args) {
-    std::lock_guard<std::mutex> lock(descriptor_lock_);
-    const auto map_descriptor = descriptors_map_.find(descriptor_id);
-    if (map_descriptor == descriptors_map_.end()) {
-      return GRALLOC1_ERROR_BAD_DESCRIPTOR;
-    }
-    const auto descriptor = map_descriptor->second;
-    (descriptor.get()->*member)(std::forward<Args>(args)...);
-    return GRALLOC1_ERROR_NONE;
-  }
-
-  static BufferManager* GetInstance() {
-    static BufferManager *instance = new BufferManager();
-    return instance;
-  }
-
- private:
-  BufferManager();
-  gralloc1_error_t MapBuffer(private_handle_t const *hnd);
-  int GetBufferType(int format);
-  int AllocateBufferLocked(const BufferDescriptor &descriptor, buffer_handle_t *handle,
-                           unsigned int bufferSize = 0);
-  uint32_t GetDataAlignment(int format, gralloc1_producer_usage_t prod_usage,
-                       gralloc1_consumer_usage_t cons_usage);
-  int GetHandleFlags(int format, gralloc1_producer_usage_t prod_usage,
-                     gralloc1_consumer_usage_t cons_usage);
-  void CreateSharedHandle(buffer_handle_t inbuffer, const BufferDescriptor &descriptor,
-                          buffer_handle_t *out_buffer);
-
-  // Imports the ion fds into the current process. Returns an error for invalid handles
-  gralloc1_error_t ImportHandleLocked(private_handle_t *hnd);
-
-  // Creates a Buffer from the valid private handle and adds it to the map
-  void RegisterHandleLocked(const private_handle_t *hnd, int ion_handle, int ion_handle_meta);
-
-  // Wrapper structure over private handle
-  // Values associated with the private handle
-  // that do not need to go over IPC can be placed here
-  // This structure is also not expected to be ABI stable
-  // unlike private_handle_t
-  struct Buffer {
-    const private_handle_t *handle = nullptr;
-    int ref_count = 1;
-    // Hold the main and metadata ion handles
-    // Freed from the allocator process
-    // and unused in the mapping process
-    int ion_handle_main = -1;
-    int ion_handle_meta = -1;
-
-    Buffer() = delete;
-    explicit Buffer(const private_handle_t* h, int ih_main = -1, int ih_meta = -1):
-        handle(h),
-        ion_handle_main(ih_main),
-        ion_handle_meta(ih_meta) {
-    }
-    void IncRef() { ++ref_count; }
-    bool DecRef() { return --ref_count == 0; }
-  };
-
-  gralloc1_error_t FreeBuffer(std::shared_ptr<Buffer> buf);
-
-  // Get the wrapper Buffer object from the handle, returns nullptr if handle is not found
-  std::shared_ptr<Buffer> GetBufferFromHandleLocked(const private_handle_t *hnd);
-
-  bool map_fb_mem_ = false;
-  Allocator *allocator_ = NULL;
-  std::mutex buffer_lock_;
-  std::mutex descriptor_lock_;
-  // TODO(user): The private_handle_t is used as a key because the unique ID generated
-  // from next_id_ is not unique across processes. The correct way to resolve this would
-  // be to use the allocator over hwbinder
-  std::unordered_map<const private_handle_t*, std::shared_ptr<Buffer>> handles_map_ = {};
-  std::unordered_map<gralloc1_buffer_descriptor_t,
-                     std::shared_ptr<BufferDescriptor>> descriptors_map_ = {};
-  std::atomic<uint64_t> next_id_;
-};
-
-}  // namespace gralloc1
-
-#endif  // __GR_BUF_MGR_H__
diff --git a/libgralloc1/gr_device_impl.cpp b/libgralloc1/gr_device_impl.cpp
deleted file mode 100644
index c900d23..0000000
--- a/libgralloc1/gr_device_impl.cpp
+++ /dev/null
@@ -1,536 +0,0 @@
-/*
- * Copyright (c) 2016-2017, The Linux Foundation. All rights reserved.
-
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *   * Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- *   * Redistributions in binary form must reproduce the above
- *     copyright notice, this list of conditions and the following
- *     disclaimer in the documentation and/or other materials provided
- *     with the distribution.
- *   * Neither the name of The Linux Foundation nor the names of its
- *     contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
- * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
- * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
- * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#define ATRACE_TAG (ATRACE_TAG_GRAPHICS | ATRACE_TAG_HAL)
-#include <cutils/log.h>
-#include <utils/Trace.h>
-#include <cutils/trace.h>
-#include <sync/sync.h>
-#include <algorithm>
-#include <sstream>
-#include <string>
-
-#include "gr_device_impl.h"
-#include "gr_buf_descriptor.h"
-#include "gralloc_priv.h"
-#include "qd_utils.h"
-#include "qdMetaData.h"
-#include "gr_utils.h"
-
-int gralloc_device_open(const struct hw_module_t *module, const char *name, hw_device_t **device);
-
-int gralloc_device_close(struct hw_device_t *device);
-
-static struct hw_module_methods_t gralloc_module_methods = {.open = gralloc_device_open};
-
-struct gralloc_module_t HAL_MODULE_INFO_SYM = {
-  .common = {
-    .tag = HARDWARE_MODULE_TAG,
-    .module_api_version = GRALLOC_MODULE_API_VERSION_1_0,
-    .hal_api_version    = HARDWARE_HAL_API_VERSION,
-    .id = GRALLOC_HARDWARE_MODULE_ID,
-    .name = "Graphics Memory Module",
-    .author = "Code Aurora Forum",
-    .methods = &gralloc_module_methods,
-    .dso = 0,
-    .reserved = {0},
-  },
-};
-
-int gralloc_device_open(const struct hw_module_t *module, const char *name, hw_device_t **device) {
-  int status = -EINVAL;
-  if (module && device && !strcmp(name, GRALLOC_HARDWARE_MODULE_ID)) {
-    gralloc1::GrallocImpl * /*gralloc1_device_t*/ dev = gralloc1::GrallocImpl::GetInstance(module);
-    *device = reinterpret_cast<hw_device_t *>(dev);
-    if (dev) {
-      status = 0;
-    } else {
-      ALOGE("Fatal error opening gralloc1 device");
-    }
-  }
-  return status;
-}
-
-namespace gralloc1 {
-
-GrallocImpl::GrallocImpl(const hw_module_t *module) {
-  common.tag = HARDWARE_DEVICE_TAG;
-  common.version = GRALLOC_MODULE_API_VERSION_1_0;
-  common.module = const_cast<hw_module_t *>(module);
-  common.close = CloseDevice;
-  getFunction = GetFunction;
-  getCapabilities = GetCapabilities;
-
-  initalized_ = Init();
-}
-
-bool GrallocImpl::Init() {
-  buf_mgr_ = BufferManager::GetInstance();
-  return buf_mgr_ != nullptr;
-}
-
-GrallocImpl::~GrallocImpl() {
-}
-
-int GrallocImpl::CloseDevice(hw_device_t *device __unused) {
-  // No-op since the gralloc device is a singleton
-  return 0;
-}
-
-void GrallocImpl::GetCapabilities(struct gralloc1_device *device, uint32_t *out_count,
-                                  int32_t  /*gralloc1_capability_t*/ *out_capabilities) {
-  if (device != nullptr && out_count != nullptr) {
-    if (out_capabilities != nullptr && *out_count >= 3) {
-      out_capabilities[0] = GRALLOC1_CAPABILITY_TEST_ALLOCATE;
-      out_capabilities[1] = GRALLOC1_CAPABILITY_LAYERED_BUFFERS;
-      out_capabilities[2] = GRALLOC1_CAPABILITY_RELEASE_IMPLY_DELETE;
-    }
-    *out_count = 3;
-  }
-  return;
-}
-
-gralloc1_function_pointer_t GrallocImpl::GetFunction(gralloc1_device_t *device, int32_t function) {
-  if (!device) {
-    return NULL;
-  }
-
-  switch (function) {
-    case GRALLOC1_FUNCTION_DUMP:
-      return reinterpret_cast<gralloc1_function_pointer_t>(Dump);
-    case GRALLOC1_FUNCTION_CREATE_DESCRIPTOR:
-      return reinterpret_cast<gralloc1_function_pointer_t>(CreateBufferDescriptor);
-    case GRALLOC1_FUNCTION_DESTROY_DESCRIPTOR:
-      return reinterpret_cast<gralloc1_function_pointer_t>(DestroyBufferDescriptor);
-    case GRALLOC1_FUNCTION_SET_CONSUMER_USAGE:
-      return reinterpret_cast<gralloc1_function_pointer_t>(SetConsumerUsage);
-    case GRALLOC1_FUNCTION_SET_DIMENSIONS:
-      return reinterpret_cast<gralloc1_function_pointer_t>(SetBufferDimensions);
-    case GRALLOC1_FUNCTION_SET_FORMAT:
-      return reinterpret_cast<gralloc1_function_pointer_t>(SetColorFormat);
-    case GRALLOC1_FUNCTION_SET_LAYER_COUNT:
-      return reinterpret_cast<gralloc1_function_pointer_t>(SetLayerCount);
-    case GRALLOC1_FUNCTION_SET_PRODUCER_USAGE:
-      return reinterpret_cast<gralloc1_function_pointer_t>(SetProducerUsage);
-    case GRALLOC1_FUNCTION_GET_BACKING_STORE:
-      return reinterpret_cast<gralloc1_function_pointer_t>(GetBackingStore);
-    case GRALLOC1_FUNCTION_GET_CONSUMER_USAGE:
-      return reinterpret_cast<gralloc1_function_pointer_t>(GetConsumerUsage);
-    case GRALLOC1_FUNCTION_GET_DIMENSIONS:
-      return reinterpret_cast<gralloc1_function_pointer_t>(GetBufferDimensions);
-    case GRALLOC1_FUNCTION_GET_FORMAT:
-      return reinterpret_cast<gralloc1_function_pointer_t>(GetColorFormat);
-    case GRALLOC1_FUNCTION_GET_LAYER_COUNT:
-      return reinterpret_cast<gralloc1_function_pointer_t>(GetLayerCount);
-    case GRALLOC1_FUNCTION_GET_PRODUCER_USAGE:
-      return reinterpret_cast<gralloc1_function_pointer_t>(GetProducerUsage);
-    case GRALLOC1_FUNCTION_GET_STRIDE:
-      return reinterpret_cast<gralloc1_function_pointer_t>(GetBufferStride);
-    case GRALLOC1_FUNCTION_ALLOCATE:
-      return reinterpret_cast<gralloc1_function_pointer_t>(AllocateBuffers);
-    case GRALLOC1_FUNCTION_RETAIN:
-      return reinterpret_cast<gralloc1_function_pointer_t>(RetainBuffer);
-    case GRALLOC1_FUNCTION_RELEASE:
-      return reinterpret_cast<gralloc1_function_pointer_t>(ReleaseBuffer);
-    case GRALLOC1_FUNCTION_GET_NUM_FLEX_PLANES:
-      return reinterpret_cast<gralloc1_function_pointer_t>(GetNumFlexPlanes);
-    case GRALLOC1_FUNCTION_LOCK:
-      return reinterpret_cast<gralloc1_function_pointer_t>(LockBuffer);
-    case GRALLOC1_FUNCTION_LOCK_FLEX:
-      return reinterpret_cast<gralloc1_function_pointer_t>(LockFlex);
-    case GRALLOC1_FUNCTION_UNLOCK:
-      return reinterpret_cast<gralloc1_function_pointer_t>(UnlockBuffer);
-    case GRALLOC1_FUNCTION_PERFORM:
-      return reinterpret_cast<gralloc1_function_pointer_t>(Gralloc1Perform);
-    default:
-      ALOGE("%s:Gralloc Error. Client Requested for unsupported function", __FUNCTION__);
-      return NULL;
-  }
-
-  return NULL;
-}
-
-gralloc1_error_t GrallocImpl::Dump(gralloc1_device_t *device, uint32_t *out_size,
-                                   char *out_buffer) {
-  if (!device || !out_size) {
-    ALOGE("Gralloc Error : device=%p", (void *)device);
-    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
-  }
-  const size_t max_dump_size = 8192;
-  if (out_buffer == nullptr) {
-    *out_size = max_dump_size;
-  } else {
-    std::ostringstream os;
-    os << "-------------------------------" << std::endl;
-    os << "QTI gralloc dump:" << std::endl;
-    os << "-------------------------------" << std::endl;
-    GrallocImpl const *dev = GRALLOC_IMPL(device);
-    dev->buf_mgr_->Dump(&os);
-    os << "-------------------------------" << std::endl;
-    auto copied = os.str().copy(out_buffer, std::min(os.str().size(), max_dump_size), 0);
-    *out_size = UINT(copied);
-  }
-
-  return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t GrallocImpl::CheckDeviceAndHandle(gralloc1_device_t *device,
-                                                   buffer_handle_t buffer) {
-  const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
-  if (!device || (private_handle_t::validate(hnd) != 0)) {
-    ALOGE("Gralloc Error : device= %p, buffer-handle=%p", (void *)device, (void *)buffer);
-    return GRALLOC1_ERROR_BAD_HANDLE;
-  }
-
-  return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t GrallocImpl::CreateBufferDescriptor(gralloc1_device_t *device,
-                                                     gralloc1_buffer_descriptor_t *out_descriptor) {
-  if (!device || !out_descriptor) {
-    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
-  }
-  GrallocImpl const *dev = GRALLOC_IMPL(device);
-  return dev->buf_mgr_->CreateBufferDescriptor(out_descriptor);
-}
-
-gralloc1_error_t GrallocImpl::DestroyBufferDescriptor(gralloc1_device_t *device,
-                                                      gralloc1_buffer_descriptor_t descriptor) {
-  if (!device) {
-    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
-  }
-  GrallocImpl const *dev = GRALLOC_IMPL(device);
-  return dev->buf_mgr_->DestroyBufferDescriptor(descriptor);
-}
-
-gralloc1_error_t GrallocImpl::SetConsumerUsage(gralloc1_device_t *device,
-                                               gralloc1_buffer_descriptor_t descriptor,
-                                               gralloc1_consumer_usage_t usage) {
-  if (!device) {
-    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
-  } else {
-    GrallocImpl const *dev = GRALLOC_IMPL(device);
-    return dev->buf_mgr_->CallBufferDescriptorFunction(descriptor,
-                                                       &BufferDescriptor::SetConsumerUsage, usage);
-  }
-}
-
-gralloc1_error_t GrallocImpl::SetBufferDimensions(gralloc1_device_t *device,
-                                                  gralloc1_buffer_descriptor_t descriptor,
-                                                  uint32_t width, uint32_t height) {
-  if (!device) {
-    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
-  } else {
-    GrallocImpl const *dev = GRALLOC_IMPL(device);
-    return dev->buf_mgr_->CallBufferDescriptorFunction(descriptor,
-                                                       &BufferDescriptor::SetDimensions,
-                                                       INT(width), INT(height));
-  }
-}
-
-gralloc1_error_t GrallocImpl::SetColorFormat(gralloc1_device_t *device,
-                                             gralloc1_buffer_descriptor_t descriptor,
-                                             int32_t format) {
-  if (!device) {
-    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
-  } else {
-    GrallocImpl const *dev = GRALLOC_IMPL(device);
-    return dev->buf_mgr_->CallBufferDescriptorFunction(descriptor,
-                                                       &BufferDescriptor::SetColorFormat, format);
-  }
-}
-
-gralloc1_error_t GrallocImpl::SetLayerCount(gralloc1_device_t *device,
-                                            gralloc1_buffer_descriptor_t descriptor,
-                                            uint32_t layer_count) {
-  if (!device) {
-    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
-  } else {
-    GrallocImpl const *dev = GRALLOC_IMPL(device);
-    return dev->buf_mgr_->CallBufferDescriptorFunction(descriptor,
-                                                       &BufferDescriptor::SetLayerCount,
-                                                       layer_count);
-  }
-}
-
-gralloc1_error_t GrallocImpl::SetProducerUsage(gralloc1_device_t *device,
-                                               gralloc1_buffer_descriptor_t descriptor,
-                                               gralloc1_producer_usage_t usage) {
-  if (!device) {
-    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
-  } else {
-    GrallocImpl const *dev = GRALLOC_IMPL(device);
-    return dev->buf_mgr_->CallBufferDescriptorFunction(descriptor,
-                                                       &BufferDescriptor::SetProducerUsage, usage);
-  }
-}
-
-gralloc1_error_t GrallocImpl::GetBackingStore(gralloc1_device_t *device, buffer_handle_t buffer,
-                                              gralloc1_backing_store_t *out_backstore) {
-  if (!device || !buffer) {
-    return GRALLOC1_ERROR_BAD_HANDLE;
-  }
-
-  *out_backstore =
-      static_cast<gralloc1_backing_store_t>(PRIV_HANDLE_CONST(buffer)->GetBackingstore());
-
-  return GRALLOC1_ERROR_NONE;
-}
-
-gralloc1_error_t GrallocImpl::GetConsumerUsage(gralloc1_device_t *device, buffer_handle_t buffer,
-                                               gralloc1_consumer_usage_t *outUsage) {
-  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
-  if (status == GRALLOC1_ERROR_NONE) {
-    *outUsage = PRIV_HANDLE_CONST(buffer)->GetConsumerUsage();
-  }
-
-  return status;
-}
-
-gralloc1_error_t GrallocImpl::GetBufferDimensions(gralloc1_device_t *device, buffer_handle_t buffer,
-                                                  uint32_t *outWidth, uint32_t *outHeight) {
-  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
-  if (status == GRALLOC1_ERROR_NONE) {
-    const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
-    *outWidth = UINT(hnd->GetUnalignedWidth());
-    *outHeight = UINT(hnd->GetUnalignedHeight());
-  }
-
-  return status;
-}
-
-gralloc1_error_t GrallocImpl::GetColorFormat(gralloc1_device_t *device, buffer_handle_t buffer,
-                                             int32_t *outFormat) {
-  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
-  if (status == GRALLOC1_ERROR_NONE) {
-    *outFormat = PRIV_HANDLE_CONST(buffer)->GetColorFormat();
-  }
-
-  return status;
-}
-
-gralloc1_error_t GrallocImpl::GetLayerCount(gralloc1_device_t *device, buffer_handle_t buffer,
-                                            uint32_t *outLayerCount) {
-  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
-  if (status == GRALLOC1_ERROR_NONE) {
-    *outLayerCount = PRIV_HANDLE_CONST(buffer)->GetLayerCount();
-  }
-
-  return status;
-}
-
-gralloc1_error_t GrallocImpl::GetProducerUsage(gralloc1_device_t *device, buffer_handle_t buffer,
-                                               gralloc1_producer_usage_t *outUsage) {
-  if (!outUsage) {
-    return GRALLOC1_ERROR_BAD_VALUE;
-  }
-
-  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
-  if (status == GRALLOC1_ERROR_NONE) {
-    const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
-    *outUsage = hnd->GetProducerUsage();
-  }
-
-  return status;
-}
-
-gralloc1_error_t GrallocImpl::GetBufferStride(gralloc1_device_t *device, buffer_handle_t buffer,
-                                              uint32_t *outStride) {
-  if (!outStride) {
-    return GRALLOC1_ERROR_BAD_VALUE;
-  }
-
-  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
-  if (status == GRALLOC1_ERROR_NONE) {
-    *outStride = UINT(PRIV_HANDLE_CONST(buffer)->GetStride());
-  }
-
-  return status;
-}
-
-gralloc1_error_t GrallocImpl::AllocateBuffers(gralloc1_device_t *device, uint32_t num_descriptors,
-                                              const gralloc1_buffer_descriptor_t *descriptors,
-                                              buffer_handle_t *out_buffers) {
-  if (!num_descriptors || !descriptors) {
-    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
-  }
-
-  if (!device) {
-    return GRALLOC1_ERROR_BAD_VALUE;
-  }
-
-  GrallocImpl const *dev = GRALLOC_IMPL(device);
-  gralloc1_error_t status = dev->buf_mgr_->AllocateBuffers(num_descriptors, descriptors,
-                                                           out_buffers);
-
-  return status;
-}
-
-gralloc1_error_t GrallocImpl::RetainBuffer(gralloc1_device_t *device, buffer_handle_t buffer) {
-  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
-  if (status == GRALLOC1_ERROR_NONE) {
-    const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
-    GrallocImpl const *dev = GRALLOC_IMPL(device);
-    status = dev->buf_mgr_->RetainBuffer(hnd);
-  }
-
-  return status;
-}
-
-gralloc1_error_t GrallocImpl::ReleaseBuffer(gralloc1_device_t *device, buffer_handle_t buffer) {
-  if (!device || !buffer) {
-    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
-  }
-
-  const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
-  GrallocImpl const *dev = GRALLOC_IMPL(device);
-  return dev->buf_mgr_->ReleaseBuffer(hnd);
-}
-
-gralloc1_error_t GrallocImpl::GetNumFlexPlanes(gralloc1_device_t *device, buffer_handle_t buffer,
-                                               uint32_t *out_num_planes) {
-  if (!out_num_planes) {
-    return GRALLOC1_ERROR_BAD_VALUE;
-  }
-
-  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
-  if (status == GRALLOC1_ERROR_NONE) {
-    GrallocImpl const *dev = GRALLOC_IMPL(device);
-    const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
-    status = dev->buf_mgr_->GetNumFlexPlanes(hnd, out_num_planes);
-  }
-  return status;
-}
-
-static inline void CloseFdIfValid(int fd) {
-  if (fd > 0) {
-    close(fd);
-  }
-}
-
-gralloc1_error_t GrallocImpl::LockBuffer(gralloc1_device_t *device, buffer_handle_t buffer,
-                                         gralloc1_producer_usage_t prod_usage,
-                                         gralloc1_consumer_usage_t cons_usage,
-                                         const gralloc1_rect_t *region, void **out_data,
-                                         int32_t acquire_fence) {
-  ATRACE_CALL();
-  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
-  if (status != GRALLOC1_ERROR_NONE || !out_data ||
-      !region) {  // currently we ignore the region/rect client wants to lock
-    CloseFdIfValid(acquire_fence);
-    return status;
-  }
-
-  if (acquire_fence > 0) {
-    ATRACE_BEGIN("fence wait");
-    int error = sync_wait(acquire_fence, 1000);
-    ATRACE_END();
-    CloseFdIfValid(acquire_fence);
-    if (error < 0) {
-      ALOGE("%s: sync_wait timedout! error = %s", __FUNCTION__, strerror(errno));
-      return GRALLOC1_ERROR_UNDEFINED;
-    }
-  }
-
-  const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
-  GrallocImpl const *dev = GRALLOC_IMPL(device);
-
-  // Either producer usage or consumer usage must be *_USAGE_NONE
-  if ((prod_usage != GRALLOC1_PRODUCER_USAGE_NONE) &&
-      (cons_usage != GRALLOC1_CONSUMER_USAGE_NONE)) {
-    // Current gralloc1 clients do not satisfy this restriction.
-    // See b/33588773 for details
-    // return GRALLOC1_ERROR_BAD_VALUE;
-  }
-
-  // TODO(user): Need to check if buffer was allocated with the same flags
-  status = dev->buf_mgr_->LockBuffer(hnd, prod_usage, cons_usage);
-  *out_data = reinterpret_cast<void *>(hnd->base);
-
-  return status;
-}
-
-gralloc1_error_t GrallocImpl::LockFlex(gralloc1_device_t *device, buffer_handle_t buffer,
-                                       gralloc1_producer_usage_t prod_usage,
-                                       gralloc1_consumer_usage_t cons_usage,
-                                       const gralloc1_rect_t *region,
-                                       struct android_flex_layout *out_flex_layout,
-                                       int32_t acquire_fence) {
-  if (!out_flex_layout) {
-    CloseFdIfValid(acquire_fence);
-    return GRALLOC1_ERROR_BAD_VALUE;
-  }
-
-  void *out_data {};
-  gralloc1_error_t status = GrallocImpl::LockBuffer(device, buffer, prod_usage, cons_usage, region,
-                                                    &out_data, acquire_fence);
-  if (status != GRALLOC1_ERROR_NONE) {
-    return status;
-  }
-
-  GrallocImpl const *dev = GRALLOC_IMPL(device);
-  const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
-  dev->buf_mgr_->GetFlexLayout(hnd, out_flex_layout);
-  return status;
-}
-
-gralloc1_error_t GrallocImpl::UnlockBuffer(gralloc1_device_t *device, buffer_handle_t buffer,
-                                           int32_t *release_fence) {
-  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
-  if (status != GRALLOC1_ERROR_NONE) {
-    return status;
-  }
-
-  if (!release_fence) {
-    return GRALLOC1_ERROR_BAD_VALUE;
-  }
-
-  const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
-  GrallocImpl const *dev = GRALLOC_IMPL(device);
-
-  *release_fence = -1;
-
-  return dev->buf_mgr_->UnlockBuffer(hnd);
-}
-
-gralloc1_error_t GrallocImpl::Gralloc1Perform(gralloc1_device_t *device, int operation, ...) {
-  if (!device) {
-    return GRALLOC1_ERROR_BAD_VALUE;
-  }
-
-  va_list args;
-  va_start(args, operation);
-  GrallocImpl const *dev = GRALLOC_IMPL(device);
-  gralloc1_error_t err = dev->buf_mgr_->Perform(operation, args);
-  va_end(args);
-
-  return err;
-}
-
-}  // namespace gralloc1
diff --git a/liblight/lights.c b/liblight/lights.c
index 115b98c..d511395 100644
--- a/liblight/lights.c
+++ b/liblight/lights.c
@@ -19,7 +19,7 @@
 
 // #define LOG_NDEBUG 0
 
-#include <cutils/log.h>
+#include <log/log.h>
 #include <cutils/properties.h>
 #include <stdint.h>
 #include <stdlib.h>
diff --git a/libqdutils/qdMetaData.cpp b/libqdutils/qdMetaData.cpp
index 3ccbc99..5c39133 100644
--- a/libqdutils/qdMetaData.cpp
+++ b/libqdutils/qdMetaData.cpp
@@ -30,7 +30,7 @@
 #include <errno.h>
 #include <string.h>
 #include <sys/mman.h>
-#include <cutils/log.h>
+#include <log/log.h>
 #include <cinttypes>
 #include <gralloc_priv.h>
 #include "qdMetaData.h"
diff --git a/libqdutils/qd_utils.h b/libqdutils/qd_utils.h
index f3b0c04..d83f273 100644
--- a/libqdutils/qd_utils.h
+++ b/libqdutils/qd_utils.h
@@ -35,7 +35,7 @@
 #include <ctype.h>
 #include <fcntl.h>
 #include <utils/Errors.h>
-#include <utils/Log.h>
+#include <log/log.h>
 
 #include <linux/fb.h>
 #include <sys/ioctl.h>
diff --git a/libqservice/IQHDMIClient.cpp b/libqservice/IQHDMIClient.cpp
index 9f5044a..6379e57 100644
--- a/libqservice/IQHDMIClient.cpp
+++ b/libqservice/IQHDMIClient.cpp
@@ -26,7 +26,7 @@
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
-#include <utils/Log.h>
+#include <log/log.h>
 #include <binder/Parcel.h>
 #include "IQHDMIClient.h"
 
diff --git a/libqservice/QService.h b/libqservice/QService.h
index bd130fa..6bb4d7d 100644
--- a/libqservice/QService.h
+++ b/libqservice/QService.h
@@ -32,7 +32,7 @@
 
 #include <utils/Errors.h>
 #include <sys/types.h>
-#include <cutils/log.h>
+#include <log/log.h>
 #include <binder/IServiceManager.h>
 #include <IQService.h>
 #include <IQClient.h>
diff --git a/sdm/include/private/hw_info_types.h b/sdm/include/private/hw_info_types.h
index 5d311d9..52bc73e 100644
--- a/sdm/include/private/hw_info_types.h
+++ b/sdm/include/private/hw_info_types.h
@@ -123,6 +123,13 @@
   kPPSplit,
 };
 
+enum HwHdrEotf {
+  kHdrEOTFInvalid = 0,
+  kHdrEOTFSDR = 0x1,
+  kHdrEOTFHdrLumRange = 0x2,
+  kHdrEOTFHDR10 = 0x4,
+  kHdrEOTFHLG = 0x8,
+};
 
 typedef std::map<HWSubBlockType, std::vector<LayerBufferFormat>> FormatsMap;
 typedef std::map<LayerBufferFormat, float> CompRatioMap;
diff --git a/sdm/include/utils/locker.h b/sdm/include/utils/locker.h
old mode 100644
new mode 100755
index 0096098..dabeb11
--- a/sdm/include/utils/locker.h
+++ b/sdm/include/utils/locker.h
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2014 - 2016, The Linux Foundation. All rights reserved.
+* Copyright (c) 2014 - 2016, 2018 The Linux Foundation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted
 * provided that the following conditions are met:
@@ -26,6 +26,7 @@
 #define __LOCKER_H__
 
 #include <stdint.h>
+#include <errno.h>
 #include <pthread.h>
 #include <sys/time.h>
 
@@ -126,12 +127,15 @@
 
   Locker() : sequence_wait_(0) {
     pthread_mutex_init(&mutex_, 0);
-    pthread_cond_init(&condition_, 0);
+    pthread_condattr_init(&cond_attr);
+    pthread_condattr_setclock(&cond_attr, CLOCK_MONOTONIC);
+    pthread_cond_init(&condition_, &cond_attr);
   }
 
   ~Locker() {
     pthread_mutex_destroy(&mutex_);
     pthread_cond_destroy(&condition_);
+    pthread_condattr_destroy(&cond_attr);
   }
 
   void Lock() { pthread_mutex_lock(&mutex_); }
@@ -139,20 +143,21 @@
   void Signal() { pthread_cond_signal(&condition_); }
   void Broadcast() { pthread_cond_broadcast(&condition_); }
   void Wait() { pthread_cond_wait(&condition_, &mutex_); }
-  int WaitFinite(int ms) {
+  int WaitFinite(uint32_t ms) {
     struct timespec ts;
-    struct timeval tv;
-    gettimeofday(&tv, NULL);
-    ts.tv_sec = tv.tv_sec + ms/1000;
-    ts.tv_nsec = tv.tv_usec*1000 + (ms%1000)*1000000;
-    ts.tv_sec += ts.tv_nsec/1000000000L;
-    ts.tv_nsec %= 1000000000L;
+    if (clock_gettime(CLOCK_MONOTONIC, &ts)) {
+       return EINVAL;
+    }
+    uint64_t ns = (uint64_t)ts.tv_nsec + (ms * 1000000L);
+    ts.tv_sec   = ts.tv_sec + (time_t)(ns / 1000000000L);
+    ts.tv_nsec  = ns % 1000000000L;
     return pthread_cond_timedwait(&condition_, &mutex_, &ts);
   }
 
  private:
   pthread_mutex_t mutex_;
   pthread_cond_t condition_;
+  pthread_condattr_t cond_attr;
   int sequence_wait_;   // This flag is set to 1 on sequence entry, 0 on exit, and -1 on cancel.
                         // Some routines will wait for sequence of function calls to finish
                         // so that capturing a transitionary snapshot of context is prevented.
diff --git a/sdm/libs/core/display_base.cpp b/sdm/libs/core/display_base.cpp
index b07c8a6..383bdba 100644
--- a/sdm/libs/core/display_base.cpp
+++ b/sdm/libs/core/display_base.cpp
@@ -155,7 +155,7 @@
     hw_layers_info.app_layer_count++;
   }
 
-  DLOGD_IF(kTagNone, "LayerStack layer_count: %d, app_layer_count: %d, gpu_target_index: %d, "
+  DLOGD_IF(kTagDisplay, "LayerStack layer_count: %d, app_layer_count: %d, gpu_target_index: %d, "
            "display type: %d", layers.size(), hw_layers_info.app_layer_count,
            hw_layers_info.gpu_target_index, display_type_);
 
diff --git a/sdm/libs/core/display_hdmi.cpp b/sdm/libs/core/display_hdmi.cpp
index 1f1a051..2076fe5 100644
--- a/sdm/libs/core/display_hdmi.cpp
+++ b/sdm/libs/core/display_hdmi.cpp
@@ -170,7 +170,6 @@
 uint32_t DisplayHDMI::GetBestConfig(HWS3DMode s3d_mode) {
   uint32_t best_index = 0, index;
   uint32_t num_modes = 0;
-  HWDisplayAttributes best_attrib;
 
   hw_intf_->GetNumDisplayAttributes(&num_modes);
 
diff --git a/sdm/libs/core/fb/hw_device.cpp b/sdm/libs/core/fb/hw_device.cpp
index 38e57d8..2c529ae 100644
--- a/sdm/libs/core/fb/hw_device.cpp
+++ b/sdm/libs/core/fb/hw_device.cpp
@@ -116,6 +116,10 @@
     device_fd_ = -1;
   }
 
+  if (stored_retire_fence >= 0) {
+    Sys::close_(stored_retire_fence);
+    stored_retire_fence = -1;
+  }
   return kErrorNone;
 }
 
diff --git a/sdm/libs/hwc2/Android.mk b/sdm/libs/hwc2/Android.mk
index bd33aff..52668c7 100644
--- a/sdm/libs/hwc2/Android.mk
+++ b/sdm/libs/hwc2/Android.mk
@@ -17,12 +17,14 @@
 LOCAL_CLANG                   := true
 
 LOCAL_SHARED_LIBRARIES        := libsdmcore libqservice libbinder libhardware libhardware_legacy \
-                                 libutils libcutils libsync libqdutils libqdMetaData libdl \
+                                 libutils libcutils libsync libqdutils libqdMetaData \
                                  libsdmutils libc++ liblog libgrallocutils libui libgpu_tonemapper \
-                                 libhidlbase libhidltransport vendor.display.config@1.0_vendor
+                                 libhidlbase libhidltransport vendor.display.config@1.0 \
+                                 android.hardware.graphics.mapper@2.0\
+                                 android.hardware.graphics.allocator@2.0
 
 ifeq ($(display_config_version), DISPLAY_CONFIG_1_1)
-LOCAL_SHARED_LIBRARIES        += vendor.display.config@1.1_vendor
+LOCAL_SHARED_LIBRARIES        += vendor.display.config@1.1
 endif
 
 LOCAL_SRC_FILES               := hwc_session.cpp \
diff --git a/sdm/libs/hwc2/hwc_buffer_allocator.cpp b/sdm/libs/hwc2/hwc_buffer_allocator.cpp
index e9839b9..55988f1 100644
--- a/sdm/libs/hwc2/hwc_buffer_allocator.cpp
+++ b/sdm/libs/hwc2/hwc_buffer_allocator.cpp
@@ -1,31 +1,31 @@
 /*
-* Copyright (c) 2015-2017, The Linux Foundation. All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions are
-* met:
-*  * Redistributions of source code must retain the above copyright
-*    notice, this list of conditions and the following disclaimer.
-*  * Redistributions in binary form must reproduce the above
-*    copyright notice, this list of conditions and the following
-*    disclaimer in the documentation and/or other materials provided
-*    with the distribution.
-*  * Neither the name of The Linux Foundation nor the names of its
-*    contributors may be used to endorse or promote products derived
-*    from this software without specific prior written permission.
-*
-* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
-* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
-* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
-* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
-* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
-* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
+ * Copyright (c) 2015-2018, The Linux Foundation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above
+ *    copyright notice, this list of conditions and the following
+ *    disclaimer in the documentation and/or other materials provided
+ *    with the distribution.
+ *  * Neither the name of The Linux Foundation nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+ * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
 
 #include <gralloc_priv.h>
 
@@ -33,75 +33,38 @@
 #include <utils/constants.h>
 #include <utils/debug.h>
 
+#include "gr_utils.h"
 #include "hwc_buffer_allocator.h"
 #include "hwc_debugger.h"
-#include "gr_utils.h"
 
 #define __CLASS__ "HWCBufferAllocator"
 
+using android::hardware::graphics::common::V1_0::PixelFormat;
+using android::hardware::graphics::mapper::V2_0::BufferDescriptor;
+using android::hardware::graphics::mapper::V2_0::Error;
+using android::hardware::hidl_handle;
+using android::hardware::hidl_vec;
+
 namespace sdm {
 
 DisplayError HWCBufferAllocator::Init() {
-  int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module_);
-  if (err != 0) {
-    DLOGE("FATAL: can not get GRALLOC module");
-    return kErrorResources;
+  allocator_ = IAllocator::getService();
+  mapper_ = IMapper::getService();
+
+  if (mapper_ == nullptr || allocator_ == nullptr) {
+    DLOGE("Unable to get mapper or allocator");
+    return kErrorCriticalResource;
   }
-
-  err = gralloc1_open(module_, &gralloc_device_);
-  if (err != 0) {
-    DLOGE("FATAL: can not open GRALLOC device");
-    return kErrorResources;
-  }
-
-  if (gralloc_device_ == nullptr) {
-    DLOGE("FATAL: gralloc device is null");
-    return kErrorResources;
-  }
-
-  CreateBufferDescriptor_ = reinterpret_cast<GRALLOC1_PFN_CREATE_DESCRIPTOR>(
-      gralloc_device_->getFunction(gralloc_device_, GRALLOC1_FUNCTION_CREATE_DESCRIPTOR));
-  DestroyBufferDescriptor_ = reinterpret_cast<GRALLOC1_PFN_DESTROY_DESCRIPTOR>(
-      gralloc_device_->getFunction(gralloc_device_, GRALLOC1_FUNCTION_DESTROY_DESCRIPTOR));
-  AllocateBuffer_ = reinterpret_cast<GRALLOC1_PFN_ALLOCATE>(
-      gralloc_device_->getFunction(gralloc_device_, GRALLOC1_FUNCTION_ALLOCATE));
-  ReleaseBuffer_ = reinterpret_cast<GRALLOC1_PFN_RELEASE>(
-      gralloc_device_->getFunction(gralloc_device_, GRALLOC1_FUNCTION_RELEASE));
-  SetBufferDimensions_ = reinterpret_cast<GRALLOC1_PFN_SET_DIMENSIONS>(
-      gralloc_device_->getFunction(gralloc_device_, GRALLOC1_FUNCTION_SET_DIMENSIONS));
-  SetBufferFormat_ = reinterpret_cast<GRALLOC1_PFN_SET_FORMAT>(
-      gralloc_device_->getFunction(gralloc_device_, GRALLOC1_FUNCTION_SET_FORMAT));
-  SetConsumerUsage_ = reinterpret_cast<GRALLOC1_PFN_SET_CONSUMER_USAGE>(
-      gralloc_device_->getFunction(gralloc_device_, GRALLOC1_FUNCTION_SET_CONSUMER_USAGE));
-  SetProducerUsage_ = reinterpret_cast<GRALLOC1_PFN_SET_PRODUCER_USAGE>(
-      gralloc_device_->getFunction(gralloc_device_, GRALLOC1_FUNCTION_SET_PRODUCER_USAGE));
-  LockBuffer_ = reinterpret_cast<GRALLOC1_PFN_LOCK>(
-      gralloc_device_->getFunction(gralloc_device_, GRALLOC1_FUNCTION_LOCK));
-  UnlockBuffer_ = reinterpret_cast<GRALLOC1_PFN_UNLOCK>(
-      gralloc_device_->getFunction(gralloc_device_, GRALLOC1_FUNCTION_UNLOCK));
-  Perform_ = reinterpret_cast<GRALLOC1_PFN_PERFORM>(
-      gralloc_device_->getFunction(gralloc_device_, GRALLOC1_FUNCTION_PERFORM));
-
   return kErrorNone;
 }
 
 DisplayError HWCBufferAllocator::Deinit() {
-  if (gralloc_device_ != nullptr) {
-    int err = gralloc1_close(gralloc_device_);
-    if (err != 0) {
-      DLOGE("FATAL: can not close GRALLOC device");
-      return kErrorResources;
-    }
-  }
   return kErrorNone;
 }
 
 DisplayError HWCBufferAllocator::AllocateBuffer(BufferInfo *buffer_info) {
-  DisplayError sdm_err = kErrorNone;
   const BufferConfig &buffer_config = buffer_info->buffer_config;
   AllocatedBufferInfo *alloc_buffer_info = &buffer_info->alloc_buffer_info;
-  uint32_t width = buffer_config.width;
-  uint32_t height = buffer_config.height;
   int format;
   uint64_t alloc_flags = 0;
   int error = SetBufferInfo(buffer_config.format, &format, &alloc_flags);
@@ -110,11 +73,11 @@
   }
 
   if (buffer_config.secure) {
-    alloc_flags |= GRALLOC1_PRODUCER_USAGE_PROTECTED;
+    alloc_flags |= BufferUsage::PROTECTED;
   }
 
   if (buffer_config.secure_camera) {
-    alloc_flags |= GRALLOC1_PRODUCER_USAGE_CAMERA;
+    alloc_flags |= BufferUsage::CAMERA_OUTPUT;
   }
 
   if (!buffer_config.cache) {
@@ -123,45 +86,51 @@
   }
 
   if (buffer_config.gfx_client) {
-    alloc_flags |= GRALLOC1_CONSUMER_USAGE_GPU_TEXTURE;
+    alloc_flags |= BufferUsage::GPU_TEXTURE;
   }
 
-  gralloc1_producer_usage_t producer_usage = static_cast<gralloc1_producer_usage_t>(alloc_flags);
-  gralloc1_consumer_usage_t consumer_usage = static_cast<gralloc1_consumer_usage_t>(alloc_flags |
-                                             GRALLOC1_CONSUMER_USAGE_HWCOMPOSER);
-  gralloc1_buffer_descriptor_t descriptor_id = {};
-  buffer_handle_t buf = nullptr;
+  alloc_flags |= BufferUsage::COMPOSER_OVERLAY;
+
+  IMapper::BufferDescriptorInfo descriptor_info;
+  descriptor_info.width = buffer_config.width;
+  descriptor_info.height = buffer_config.height;
+  descriptor_info.layerCount = 1;
+  descriptor_info.format = static_cast<PixelFormat>(format);
+  descriptor_info.usage = alloc_flags;
+  auto descriptor = BufferDescriptor();
+  auto hidl_err = Error::NONE;
+
+  mapper_->createDescriptor(descriptor_info, [&](const auto &_error, const auto &_descriptor) {
+    hidl_err = _error;
+    descriptor = _descriptor;
+  });
+  if (hidl_err != Error::NONE) {
+    DLOGE("Failed to create descriptor");
+    return kErrorMemory;
+  }
+
+  hidl_handle raw_handle = nullptr;
   private_handle_t *hnd = nullptr;
 
-  // CreateBuffer
-  if (CreateBufferDescriptor_(gralloc_device_, &descriptor_id) != GRALLOC1_ERROR_NONE) {
-    DLOGE("CreateBufferDescriptor failed gr_device=%p", gralloc_device_);
-    return kErrorParameters;
+  allocator_->allocate(descriptor, 1,
+                       [&](const auto &_error, const auto &_stride, const auto &_buffers) {
+                         hidl_err = _error;
+                         raw_handle = _buffers[0];
+                       });
+  if (hidl_err != Error::NONE) {
+    DLOGE("Failed to allocate buffer");
+    return kErrorMemory;
   }
-  if (SetBufferDimensions_(gralloc_device_, descriptor_id, width, height) != GRALLOC1_ERROR_NONE) {
-    DLOGE("SetBufferDimensions failed gr_device=%x desc=%d", gralloc_device_, descriptor_id);
-    sdm_err = kErrorParameters;
-    goto CleanupOnError;
-  }
-  if (SetBufferFormat_(gralloc_device_, descriptor_id, format) != GRALLOC1_ERROR_NONE) {
-    DLOGE("SetBufferFormat failed gr_device=%x desc=%d", gralloc_device_, descriptor_id);
-    sdm_err = kErrorParameters;
-    goto CleanupOnError;
-  }
-  if (SetConsumerUsage_(gralloc_device_, descriptor_id, consumer_usage) != GRALLOC1_ERROR_NONE) {
-    DLOGE("SetConsumerUsage failed gr_device=%x desc=%d", gralloc_device_, descriptor_id);
-    sdm_err = kErrorParameters;
-    goto CleanupOnError;
-  }
-  if (SetProducerUsage_(gralloc_device_, descriptor_id, producer_usage) != GRALLOC1_ERROR_NONE) {
-    DLOGE("SetProducerUsage failed gr_device=%x desc=%d", gralloc_device_, descriptor_id);
-    sdm_err = kErrorParameters;
-    goto CleanupOnError;
-  }
-  if (AllocateBuffer_(gralloc_device_, 1, &descriptor_id, &buf) != GRALLOC1_ERROR_NONE) {
-    DLOGE("AllocateBuffer failed gr_device=%x desc=%d", gralloc_device_, descriptor_id);
-    sdm_err = kErrorMemory;
-    goto CleanupOnError;
+
+  const native_handle_t *buf = nullptr;
+  mapper_->importBuffer(raw_handle, [&](const auto &_error, const auto &_buffer) {
+    hidl_err = _error;
+    buf = static_cast<const native_handle_t *>(_buffer);
+  });
+
+  if (hidl_err != Error::NONE) {
+    DLOGE("Failed to import buffer into HWC");
+    return kErrorMemory;
   }
 
   hnd = (private_handle_t *)buf;  // NOLINT
@@ -172,45 +141,45 @@
   alloc_buffer_info->size = hnd->size;
 
   buffer_info->private_data = reinterpret_cast<void *>(hnd);
-CleanupOnError:
-  DestroyBufferDescriptor_(gralloc_device_, descriptor_id);
-  return sdm_err;
+  return kErrorNone;
 }
 
 DisplayError HWCBufferAllocator::FreeBuffer(BufferInfo *buffer_info) {
   DisplayError err = kErrorNone;
-  buffer_handle_t hnd = static_cast<buffer_handle_t>(buffer_info->private_data);
-  ReleaseBuffer_(gralloc_device_, hnd);
-  AllocatedBufferInfo *alloc_buffer_info = &buffer_info->alloc_buffer_info;
+  auto hnd = reinterpret_cast<void *>(buffer_info->private_data);
+  mapper_->freeBuffer(hnd);
+  AllocatedBufferInfo &alloc_buffer_info = buffer_info->alloc_buffer_info;
 
-  alloc_buffer_info->fd = -1;
-  alloc_buffer_info->stride = 0;
-  alloc_buffer_info->size = 0;
+  alloc_buffer_info.fd = -1;
+  alloc_buffer_info.stride = 0;
+  alloc_buffer_info.size = 0;
   buffer_info->private_data = NULL;
   return err;
 }
 
 void HWCBufferAllocator::GetCustomWidthAndHeight(const private_handle_t *handle, int *width,
                                                  int *height) {
-  Perform_(gralloc_device_, GRALLOC_MODULE_PERFORM_GET_CUSTOM_STRIDE_AND_HEIGHT_FROM_HANDLE, handle,
-           width, height);
+  *width = handle->width;
+  *height = handle->height;
+  gralloc::GetCustomDimensions(const_cast<private_handle_t *>(handle), width, height);
 }
 
 void HWCBufferAllocator::GetAlignedWidthAndHeight(int width, int height, int format,
                                                   uint32_t alloc_type, int *aligned_width,
                                                   int *aligned_height) {
-  int tile_enabled;
-  gralloc1_producer_usage_t producer_usage = GRALLOC1_PRODUCER_USAGE_NONE;
-  gralloc1_consumer_usage_t consumer_usage = GRALLOC1_CONSUMER_USAGE_NONE;
+  uint64_t usage = 0;
   if (alloc_type & GRALLOC_USAGE_HW_FB) {
-    consumer_usage = GRALLOC1_CONSUMER_USAGE_CLIENT_TARGET;
+    usage |= BufferUsage::COMPOSER_CLIENT_TARGET;
   }
   if (alloc_type & GRALLOC_USAGE_PRIVATE_ALLOC_UBWC) {
-    producer_usage = GRALLOC_USAGE_PRIVATE_ALLOC_UBWC;
+    usage |= GRALLOC_USAGE_PRIVATE_ALLOC_UBWC;
   }
-
-  Perform_(gralloc_device_, GRALLOC_MODULE_PERFORM_GET_ATTRIBUTES, width, height, format,
-           producer_usage, consumer_usage, aligned_width, aligned_height, &tile_enabled);
+  uint32_t aligned_w = UINT(width);
+  uint32_t aligned_h = UINT(height);
+  gralloc::BufferInfo info(width, height, format, usage);
+  gralloc::GetAlignedWidthAndHeight(info, &aligned_w, &aligned_h);
+  *aligned_width = INT(aligned_w);
+  *aligned_height = INT(aligned_h);
 }
 
 uint32_t HWCBufferAllocator::GetBufferSize(BufferInfo *buffer_info) {
@@ -235,12 +204,7 @@
   }
 
   uint32_t aligned_width = 0, aligned_height = 0, buffer_size = 0;
-  gralloc1_producer_usage_t producer_usage = GRALLOC1_PRODUCER_USAGE_NONE;
-  gralloc1_consumer_usage_t consumer_usage = GRALLOC1_CONSUMER_USAGE_NONE;
-  // TODO(user): Currently both flags are treated similarly in gralloc
-  producer_usage = gralloc1_producer_usage_t(alloc_flags);
-  consumer_usage = gralloc1_consumer_usage_t(alloc_flags);
-  gralloc1::BufferInfo info(width, height, format, producer_usage, consumer_usage);
+  gralloc::BufferInfo info(width, height, format, alloc_flags);
   GetBufferSizeAndDimensions(info, &buffer_size, &aligned_width, &aligned_height);
   return buffer_size;
 }
@@ -391,12 +355,7 @@
   }
 
   uint32_t aligned_width = 0, aligned_height = 0, buffer_size = 0;
-  gralloc1_producer_usage_t producer_usage = GRALLOC1_PRODUCER_USAGE_NONE;
-  gralloc1_consumer_usage_t consumer_usage = GRALLOC1_CONSUMER_USAGE_NONE;
-  // TODO(user): Currently both flags are treated similarly in gralloc
-  producer_usage = gralloc1_producer_usage_t(alloc_flags);
-  consumer_usage = gralloc1_consumer_usage_t(alloc_flags);
-  gralloc1::BufferInfo info(width, height, format, producer_usage, consumer_usage);
+  gralloc::BufferInfo info(width, height, format, alloc_flags);
   GetBufferSizeAndDimensions(info, &buffer_size, &aligned_width, &aligned_height);
   allocated_buffer_info->stride = UINT32(aligned_width);
   allocated_buffer_info->aligned_width = UINT32(aligned_width);
@@ -423,7 +382,7 @@
     hnd.flags = private_handle_t::PRIV_FLAGS_UBWC_ALIGNED;
   }
 
-  int ret = gralloc1::GetBufferLayout(&hnd, stride, offset, num_planes);
+  int ret = gralloc::GetBufferLayout(&hnd, stride, offset, num_planes);
   if (ret < 0) {
     DLOGE("GetBufferLayout failed");
     return kErrorParameters;
@@ -433,24 +392,42 @@
 }
 
 DisplayError HWCBufferAllocator::MapBuffer(const private_handle_t *handle, int acquire_fence) {
-  void* buffer_ptr = NULL;
-  const gralloc1_rect_t accessRegion = {
-        .left = 0,
-        .top = 0,
-        .width = 0,
-        .height = 0
-  };
-  LockBuffer_(gralloc_device_, handle, GRALLOC1_PRODUCER_USAGE_CPU_READ,
-              GRALLOC1_CONSUMER_USAGE_NONE, &accessRegion, &buffer_ptr, acquire_fence);
+  void *buffer_ptr = NULL;
+  const IMapper::Rect access_region = {.left = 0, .top = 0, .width = 0, .height = 0};
+
+  NATIVE_HANDLE_DECLARE_STORAGE(acquire_fence_storage, 1, 0);
+  hidl_handle acquire_fence_handle;
+  if (acquire_fence >= 0) {
+    auto h = native_handle_init(acquire_fence_storage, 1, 0);
+    h->data[0] = acquire_fence;
+    acquire_fence_handle = h;
+  }
+
+  auto hnd = const_cast<private_handle_t *>(handle);
+  mapper_->lock(reinterpret_cast<void *>(hnd), (uint64_t)BufferUsage::CPU_READ_OFTEN,
+                access_region, acquire_fence_handle, [&](const auto &_error, const auto &_buffer) {
+                  if (_error == Error::NONE) {
+                    buffer_ptr = _buffer;
+                  }
+                });
+
   if (!buffer_ptr) {
     return kErrorUndefined;
   }
-
   return kErrorNone;
 }
 
-DisplayError HWCBufferAllocator::UnmapBuffer(const private_handle_t *handle, int* release_fence) {
-  return (DisplayError)(UnlockBuffer_(gralloc_device_, handle, release_fence));
+DisplayError HWCBufferAllocator::UnmapBuffer(const private_handle_t *handle, int *release_fence) {
+  DisplayError err = kErrorNone;
+  *release_fence = -1;
+  auto hnd = const_cast<private_handle_t *>(handle);
+  mapper_->unlock(reinterpret_cast<void *>(hnd),
+                  [&](const auto &_error, const auto &_release_fence) {
+                    if (_error != Error::NONE) {
+                      err = kErrorUndefined;
+                    }
+                  });
+  return err;
 }
 
 }  // namespace sdm
diff --git a/sdm/libs/hwc2/hwc_buffer_allocator.h b/sdm/libs/hwc2/hwc_buffer_allocator.h
index 7df88a4..2846b89 100644
--- a/sdm/libs/hwc2/hwc_buffer_allocator.h
+++ b/sdm/libs/hwc2/hwc_buffer_allocator.h
@@ -1,41 +1,44 @@
 /*
-* Copyright (c) 2015-2017, The Linux Foundation. All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions are
-* met:
-*  * Redistributions of source code must retain the above copyright
-*    notice, this list of conditions and the following disclaimer.
-*  * Redistributions in binary form must reproduce the above
-*    copyright notice, this list of conditions and the following
-*    disclaimer in the documentation and/or other materials provided
-*    with the distribution.
-*  * Neither the name of The Linux Foundation nor the names of its
-*    contributors may be used to endorse or promote products derived
-*    from this software without specific prior written permission.
-*
-* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
-* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
-* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
-* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
-* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
-* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-#ifdef USE_GRALLOC1
+ * Copyright (c) 2015-2018, The Linux Foundation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above
+ *    copyright notice, this list of conditions and the following
+ *    disclaimer in the documentation and/or other materials provided
+ *    with the distribution.
+ *  * Neither the name of The Linux Foundation nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+ * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
 #ifndef __HWC_BUFFER_ALLOCATOR_H__
 #define __HWC_BUFFER_ALLOCATOR_H__
 
 #include <fcntl.h>
 #include <sys/mman.h>
 
-#include <hardware/gralloc1.h>
+#include <android/hardware/graphics/allocator/2.0/IAllocator.h>
+#include <android/hardware/graphics/mapper/2.0/IMapper.h>
 #include "gralloc_priv.h"
 
+using android::hardware::graphics::allocator::V2_0::IAllocator;
+using android::hardware::graphics::mapper::V2_0::IMapper;
+
 namespace sdm {
 
 template <class Type>
@@ -56,32 +59,16 @@
                                 int *aligned_width, int *aligned_height);
   DisplayError GetAllocatedBufferInfo(const BufferConfig &buffer_config,
                                       AllocatedBufferInfo *allocated_buffer_info);
-  DisplayError GetBufferLayout(const AllocatedBufferInfo &buf_info,
-                               uint32_t stride[4], uint32_t offset[4],
-                               uint32_t *num_planes);
+  DisplayError GetBufferLayout(const AllocatedBufferInfo &buf_info, uint32_t stride[4],
+                               uint32_t offset[4], uint32_t *num_planes);
   int SetBufferInfo(LayerBufferFormat format, int *target, uint64_t *flags);
   DisplayError MapBuffer(const private_handle_t *handle, int acquire_fence);
-  DisplayError UnmapBuffer(const private_handle_t *handle, int* release_fence);
+  DisplayError UnmapBuffer(const private_handle_t *handle, int *release_fence);
 
  private:
-  gralloc1_device_t *gralloc_device_ = nullptr;
-  const hw_module_t *module_ = nullptr;
-  GRALLOC1_PFN_CREATE_DESCRIPTOR CreateBufferDescriptor_ = nullptr;
-  GRALLOC1_PFN_DESTROY_DESCRIPTOR DestroyBufferDescriptor_ = nullptr;
-  GRALLOC1_PFN_ALLOCATE AllocateBuffer_ = nullptr;
-  GRALLOC1_PFN_RELEASE ReleaseBuffer_ = nullptr;
-  GRALLOC1_PFN_SET_DIMENSIONS SetBufferDimensions_ = nullptr;
-  GRALLOC1_PFN_SET_FORMAT SetBufferFormat_ = nullptr;
-  GRALLOC1_PFN_SET_CONSUMER_USAGE SetConsumerUsage_ = nullptr;
-  GRALLOC1_PFN_SET_PRODUCER_USAGE SetProducerUsage_ = nullptr;
-  GRALLOC1_PFN_LOCK LockBuffer_ = nullptr;
-  GRALLOC1_PFN_UNLOCK UnlockBuffer_ = nullptr;
-  GRALLOC1_PFN_PERFORM Perform_ = nullptr;
+  android::sp<IMapper> mapper_;
+  android::sp<IAllocator> allocator_;
 };
 
 }  // namespace sdm
 #endif  // __HWC_BUFFER_ALLOCATOR_H__
-#else
-#include "../hwc/hwc_buffer_allocator.h"
-#endif  // __HWC_BUFFER_ALLOCATOR_H__
-
diff --git a/sdm/libs/hwc2/hwc_debugger.h b/sdm/libs/hwc2/hwc_debugger.h
index 04cbfa7..3a3d787 100644
--- a/sdm/libs/hwc2/hwc_debugger.h
+++ b/sdm/libs/hwc2/hwc_debugger.h
@@ -34,7 +34,7 @@
 
 #include <core/sdm_types.h>
 #include <core/debug_interface.h>
-#include <cutils/log.h>
+#include <log/log.h>
 #include <utils/Trace.h>
 #include <bitset>
 
diff --git a/sdm/libs/hwc2/hwc_display.cpp b/sdm/libs/hwc2/hwc_display.cpp
index 0c48b05..142b84b 100644
--- a/sdm/libs/hwc2/hwc_display.cpp
+++ b/sdm/libs/hwc2/hwc_display.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2014-2018, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright 2015 The Android Open Source Project
@@ -42,10 +42,6 @@
 #include "hwc_tonemapper.h"
 #include "hwc_session.h"
 
-#ifndef USE_GRALLOC1
-#include <gr.h>
-#endif
-
 #ifdef QTI_BSP
 #include <hardware/display_defs.h>
 #endif
@@ -434,6 +430,8 @@
   *out_layer_id = layer->GetId();
   geometry_changes_ |= GeometryChanges::kAdded;
   validated_ = false;
+  layer_stack_invalid_ = true;
+
   return HWC2::Error::None;
 }
 
@@ -466,6 +464,8 @@
 
   geometry_changes_ |= GeometryChanges::kRemoved;
   validated_ = false;
+  layer_stack_invalid_ = true;
+
   return HWC2::Error::None;
 }
 
@@ -517,11 +517,7 @@
     const private_handle_t *handle =
         reinterpret_cast<const private_handle_t *>(layer->input_buffer.buffer_id);
     if (handle) {
-#ifdef USE_GRALLOC1
       if (handle->buffer_type == BUFFER_TYPE_VIDEO) {
-#else
-      if (handle->bufferType == BUFFER_TYPE_VIDEO) {
-#endif
         layer_stack_.flags.video_present = true;
       }
       // TZ Protected Buffer - L1
@@ -633,6 +629,8 @@
   }
   // set secure display
   SetSecureDisplay(secure_display_active);
+
+  layer_stack_invalid_ = false;
 }
 
 void HWCDisplay::BuildSolidFillStack() {
@@ -1214,10 +1212,6 @@
 
 
 HWC2::Error HWCDisplay::CommitLayerStack(void) {
-  if (shutdown_pending_ || layer_set_.empty()) {
-    return HWC2::Error::None;
-  }
-
   if (skip_validate_ && !CanSkipValidate()) {
     validated_ = false;
   }
@@ -1227,6 +1221,10 @@
     return HWC2::Error::NotValidated;
   }
 
+  if (shutdown_pending_ || layer_set_.empty()) {
+    return HWC2::Error::None;
+  }
+
   DumpInputBuffers();
 
   if (!flush_) {
@@ -1316,8 +1314,11 @@
       close(layer_buffer->acquire_fence_fd);
       layer_buffer->acquire_fence_fd = -1;
     }
+
+    layer->request.flags = {};
   }
 
+  client_target_->GetSDMLayer()->request.flags = {};
   *out_retire_fence = -1;
   if (!flush_) {
     // if swapinterval property is set to 0 then close and reset the list retire fence
@@ -1337,8 +1338,6 @@
   geometry_changes_ = GeometryChanges::kNone;
   flush_ = false;
 
-  ClearRequestFlags();
-
   return status;
 }
 
@@ -1676,13 +1675,8 @@
     flags |= private_handle_t::PRIV_FLAGS_UBWC_ALIGNED;
   }
 
-#ifdef USE_GRALLOC1
   buffer_allocator_->GetAlignedWidthAndHeight(INT(x_pixels), INT(y_pixels), format, usage,
                                               &aligned_width, &aligned_height);
-#else
-  AdrenoMemInfo::getInstance().getAlignedWidthAndHeight(INT(x_pixels), INT(y_pixels), format,
-                                                        INT(usage), aligned_width, aligned_height);
-#endif
 
   // TODO(user): How does the dirty region get set on the client target? File bug on Google
   client_target_layer->composition = kCompositionGPUTarget;
@@ -2016,12 +2010,6 @@
   return display_class_;
 }
 
-void HWCDisplay::ClearRequestFlags() {
-  for (Layer *layer : layer_stack_.layers) {
-    layer->request.flags = {};
-  }
-}
-
 std::string HWCDisplay::Dump() {
   std::ostringstream os;
   os << "\n------------HWC----------------\n";
@@ -2045,6 +2033,11 @@
        << std::endl;
   }
 
+  if (layer_stack_invalid_) {
+    os << "\n Layers added or removed but not reflected to SDM's layer stack yet\n";
+    return os.str();
+  }
+
   if (color_mode_) {
     os << "\n----------Color Modes---------\n";
     color_mode_->Dump(&os);
diff --git a/sdm/libs/hwc2/hwc_display.h b/sdm/libs/hwc2/hwc_display.h
index 263b69f..a5e1457 100644
--- a/sdm/libs/hwc2/hwc_display.h
+++ b/sdm/libs/hwc2/hwc_display.h
@@ -249,7 +249,6 @@
   bool IsSurfaceUpdated(const std::vector<LayerRect> &dirty_regions);
   bool IsLayerUpdating(const Layer *layer);
   uint32_t SanitizeRefreshRate(uint32_t req_refresh_rate);
-  virtual void ClearRequestFlags();
   virtual void GetUnderScanConfig() { }
 
   enum {
@@ -258,6 +257,7 @@
   };
 
   bool validated_ = false;
+  bool layer_stack_invalid_ = true;
   CoreInterface *core_intf_ = nullptr;
   HWCCallbacks *callbacks_  = nullptr;
   HWCBufferAllocator *buffer_allocator_ = NULL;
diff --git a/sdm/libs/hwc2/hwc_display_primary.cpp b/sdm/libs/hwc2/hwc_display_primary.cpp
index ee6f03e..1f2fdf6 100644
--- a/sdm/libs/hwc2/hwc_display_primary.cpp
+++ b/sdm/libs/hwc2/hwc_display_primary.cpp
@@ -207,7 +207,10 @@
   }
 
   if (layer_set_.empty()) {
-    flush_ = true;
+    // Avoid flush for Command mode panel.
+    DisplayConfigFixedInfo display_config;
+    display_intf_->GetConfig(&display_config);
+    flush_ = !display_config.is_cmdmode;
     return status;
   }
 
diff --git a/sdm/libs/hwc2/hwc_display_virtual.cpp b/sdm/libs/hwc2/hwc_display_virtual.cpp
index e1949ba..11193bb 100644
--- a/sdm/libs/hwc2/hwc_display_virtual.cpp
+++ b/sdm/libs/hwc2/hwc_display_virtual.cpp
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2014-2017, The Linux Foundation. All rights reserved.
+* Copyright (c) 2014-2018, The Linux Foundation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
@@ -31,9 +31,6 @@
 #include <utils/debug.h>
 #include <sync/sync.h>
 #include <stdarg.h>
-#ifndef USE_GRALLOC1
-#include <gr.h>
-#endif
 
 #include "hwc_display_virtual.h"
 #include "hwc_debugger.h"
diff --git a/sdm/libs/hwc2/hwc_layers.cpp b/sdm/libs/hwc2/hwc_layers.cpp
index b42eda7..cfc1cb0 100644
--- a/sdm/libs/hwc2/hwc_layers.cpp
+++ b/sdm/libs/hwc2/hwc_layers.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2014-2018, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright 2015 The Android Open Source Project
@@ -17,16 +17,12 @@
  * limitations under the License.
  */
 
+#include "hwc_layers.h"
+#include <utils/debug.h>
 #include <stdint.h>
 #include <utility>
-#include <qdMetaData.h>
-
-#include "hwc_layers.h"
-#ifndef USE_GRALLOC1
-#include <gr.h>
-#endif
-#include <utils/debug.h>
 #include <cmath>
+#include <qdMetaData.h>
 
 #define __CLASS__ "HWCLayer"
 
@@ -180,12 +176,15 @@
 HWCLayer::~HWCLayer() {
   // Close any fences left for this layer
   while (!release_fences_.empty()) {
-    close(release_fences_.front());
+    ::close(release_fences_.front());
     release_fences_.pop();
   }
   if (layer_) {
     if (layer_->input_buffer.acquire_fence_fd >= 0) {
-      close(layer_->input_buffer.acquire_fence_fd);
+      ::close(layer_->input_buffer.acquire_fence_fd);
+    }
+    if (buffer_fd_ >= 0) {
+      ::close(buffer_fd_);
     }
     delete layer_;
   }
@@ -217,11 +216,7 @@
 
   LayerBuffer *layer_buffer = &layer_->input_buffer;
   int aligned_width, aligned_height;
-#ifdef USE_GRALLOC1
   buffer_allocator_->GetCustomWidthAndHeight(handle, &aligned_width, &aligned_height);
-#else
-  AdrenoMemInfo::getInstance().getAlignedWidthAndHeight(handle, aligned_width, aligned_height);
-#endif
 
   LayerBufferFormat format = GetSDMFormat(handle->format, handle->flags);
   if ((format != layer_buffer->format) || (UINT32(aligned_width) != layer_buffer->width) ||
@@ -257,10 +252,14 @@
   layer_buffer->flags.secure_display = secure_display;
 
   if (layer_buffer->acquire_fence_fd >= 0) {
-    close(layer_buffer->acquire_fence_fd);
+    ::close(layer_buffer->acquire_fence_fd);
   }
   layer_buffer->acquire_fence_fd = acquire_fence;
-  layer_buffer->planes[0].fd = handle->fd;
+  if (buffer_fd_ >= 0) {
+    ::close(buffer_fd_);
+  }
+  buffer_fd_ = ::dup(handle->fd);
+  layer_buffer->planes[0].fd = buffer_fd_;
   layer_buffer->planes[0].offset = handle->offset;
   layer_buffer->planes[0].stride = UINT32(handle->width);
   layer_buffer->size = handle->size;
diff --git a/sdm/libs/hwc2/hwc_layers.h b/sdm/libs/hwc2/hwc_layers.h
index 5f5792f..ed03c50 100644
--- a/sdm/libs/hwc2/hwc_layers.h
+++ b/sdm/libs/hwc2/hwc_layers.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2014-2018, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright 2015 The Android Open Source Project
@@ -111,6 +111,7 @@
   LayerRect dst_rect_ = {};
   bool needs_validate_ = true;
   bool single_buffer_ = false;
+  int buffer_fd_ = -1;
 
   // Composition requested by client(SF)
   HWC2::Composition client_requested_ = HWC2::Composition::Device;
diff --git a/sdm/libs/hwc2/hwc_session.cpp b/sdm/libs/hwc2/hwc_session.cpp
index fdb8358..02e2129 100644
--- a/sdm/libs/hwc2/hwc_session.cpp
+++ b/sdm/libs/hwc2/hwc_session.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2014-2018, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright 2015 The Android Open Source Project
@@ -162,7 +162,7 @@
 
   DisplayError error = buffer_allocator_.Init();
   if (error != kErrorNone) {
-    ALOGE("%s::%s: Buffer allocaor initialization failed. Error = %d",
+    ALOGE("%s::%s: Buffer allocator initialization failed. Error = %d",
           __CLASS__, __FUNCTION__, error);
     return -EINVAL;
   }
@@ -804,7 +804,7 @@
   }
 
   // Sequence locking currently begins on Validate, so cancel the sequence lock on failures
-  if (status != HWC2::Error::None) {
+  if (status != HWC2::Error::None && status != HWC2::Error::HasChanges) {
     SEQUENCE_CANCEL_SCOPE_LOCK(locker_[display]);
   }