gralloc: Add allocator and mapper HALs

Implement the hidl .hal interfaces directly instead of using the
default shims.
This is required since new additions to .hal will no longer be
added to the legacy gralloc1 C header.

Change-Id: If577a14f75d7d13da0ff656c96ab451d21c910ce
diff --git a/gralloc/Android.mk b/gralloc/Android.mk
index 49ceae5..c0f154c 100644
--- a/gralloc/Android.mk
+++ b/gralloc/Android.mk
@@ -7,21 +7,16 @@
 LOCAL_VENDOR_MODULE           := true
 LOCAL_MODULE_RELATIVE_PATH    := hw
 LOCAL_MODULE_TAGS             := optional
-LOCAL_C_INCLUDES              := $(common_includes) \
-                                 external/libcxx/include/ \
-                                 system/core/libion/include/ \
-                                 system/core/libion/kernel-headers/ \
-                                 $(TARGET_OUT_INTERMEDIATES)/KERNEL_OBJ/usr/include
+LOCAL_C_INCLUDES              := $(common_includes) $(kernel_includes)
 
 LOCAL_HEADER_LIBRARIES        := display_headers
-LOCAL_SHARED_LIBRARIES        := $(common_libs) libqdMetaData libsync libgrallocutils libion
-LOCAL_CFLAGS                  := $(common_flags) -DLOG_TAG=\"qdgralloc\" -Wall -std=c++11 -Werror
+LOCAL_SHARED_LIBRARIES        := $(common_libs) libqdMetaData libsync libgrallocutils \
+                                 libgralloccore \
+                                 android.hardware.graphics.mapper@2.0
+LOCAL_CFLAGS                  := $(common_flags) -DLOG_TAG=\"qdgralloc\" -Wall -Werror
 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_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)
@@ -33,8 +28,85 @@
 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_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) \
+                                 system/core/libion/include \
+                                 system/core/libion/kernel-headers \
+                                 $(kernel_includes)
+
+LOCAL_HEADER_LIBRARIES        := display_headers
+LOCAL_SHARED_LIBRARIES        := $(common_libs) libqdMetaData libdl libgrallocutils libion \
+                                  android.hardware.graphics.mapper@2.0
+LOCAL_CFLAGS                  := $(common_flags) -DLOG_TAG=\"qdgralloc\" -Wno-sign-conversion
+LOCAL_ADDITIONAL_DEPENDENCIES := $(common_deps) $(kernel_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)
+
+
+ifeq ($(qti_mapper_version), QTI_MAPPER_1_0)
+#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 \
+                                  vendor.qti.hardware.display.mapper@1.0 \
+                                  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)
+endif  # QTI_MAPPER_1_0
+
+ifeq ($(qti_allocator_version), QTI_ALLOCATOR_1_0)
+#allocator service
+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 \
+                                 vendor.qti.hardware.display.allocator@1.0 \
+                                 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)
+endif  # QTI_ALLOCATOR_1_0
diff --git a/gralloc/QtiAllocator.cpp b/gralloc/QtiAllocator.cpp
new file mode 100644
index 0000000..e58b791
--- /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.
+
+IQtiAllocator *HIDL_FETCH_IQtiAllocator(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..be6aa25
--- /dev/null
+++ b/gralloc/QtiAllocator.h
@@ -0,0 +1,84 @@
+/*
+ * 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 <vendor/qti/hardware/display/allocator/1.0/IQtiAllocator.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 ::vendor::qti::hardware::display::allocator::V1_0::IQtiAllocator;
+using gralloc::BufferManager;
+
+class QtiAllocator : public IQtiAllocator {
+ 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" IQtiAllocator *HIDL_FETCH_IQtiAllocator(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..ec07ce0
--- /dev/null
+++ b/gralloc/QtiMapper.cpp
@@ -0,0 +1,347 @@
+/*
+ * 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();
+}
+
+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;
+}
+
+// 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);
+}
+
+IQtiMapper *HIDL_FETCH_IQtiMapper(const char * /* name */) {
+  ALOGD_IF(DEBUG, "Fetching QtiMapper");
+  return new QtiMapper();
+}
+}  // 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..276f86e
--- /dev/null
+++ b/gralloc/QtiMapper.h
@@ -0,0 +1,105 @@
+/*
+ * 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 <vendor/qti/hardware/display/mapper/1.0/IQtiMapper.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 ::vendor::qti::hardware::display::mapper::V1_0::IQtiMapper;
+using gralloc::BufferManager;
+
+class QtiMapper : public IQtiMapper {
+ 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;
+  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;
+
+ 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);
+extern "C" IQtiMapper *HIDL_FETCH_IQtiMapper(const char *name);
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace mapper
+}  // namespace display
+}  // namespace hardware
+}  // namespace qti
+}  // namespace vendor
+
+#endif  // __QTIMAPPER_H__
diff --git a/gralloc/gr_adreno_info.cpp b/gralloc/gr_adreno_info.cpp
index bdd1e8b..9484d14 100644
--- a/gralloc/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
@@ -32,14 +32,14 @@
 #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,
@@ -212,7 +212,6 @@
        return ADRENO_PIXELFORMAT_A2B10G10R10_UNORM;
     case HAL_PIXEL_FORMAT_RGBA_FP16:
        return ADRENO_PIXELFORMAT_R16G16B16A16_FLOAT;
-
     case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:
       return ADRENO_PIXELFORMAT_NV12;
     case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS:
@@ -224,7 +223,6 @@
     case HAL_PIXEL_FORMAT_YCbCr_420_P010_UBWC:
     case HAL_PIXEL_FORMAT_YCbCr_420_P010_VENUS:
       return ADRENO_PIXELFORMAT_P010;
-
     default:
       ALOGE("%s: No map for format: 0x%x", __FUNCTION__, hal_format);
       break;
@@ -233,4 +231,4 @@
   return ADRENO_PIXELFORMAT_UNKNOWN;
 }
 
-}  // namespace gralloc1
+}  // namespace gralloc
diff --git a/gralloc/gr_adreno_info.h b/gralloc/gr_adreno_info.h
index 83966ae..a454d15 100644
--- a/gralloc/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/gralloc/gr_allocator.cpp b/gralloc/gr_allocator.cpp
index 7a54187..65ec506 100644
--- a/gralloc/gr_allocator.cpp
+++ b/gralloc/gr_allocator.cpp
@@ -31,8 +31,8 @@
 #include <algorithm>
 #include <vector>
 
-#include "gr_utils.h"
 #include "gr_allocator.h"
+#include "gr_utils.h"
 #include "gralloc_priv.h"
 
 #include "qd_utils.h"
@@ -69,18 +69,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();
@@ -97,14 +96,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) {
@@ -132,8 +129,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);
   }
@@ -151,7 +147,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;
@@ -163,10 +159,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)) {
@@ -190,47 +184,46 @@
   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) {
-      if (prod_usage & GRALLOC1_PRODUCER_USAGE_PRIVATE_VIDEO_NV21_ENCODER) {
+    } else if (usage & BufferUsage::VIDEO_ENCODER) {
+      if (usage & GRALLOC_USAGE_PRIVATE_VIDEO_NV21_ENCODER) {
         gr_format = HAL_PIXEL_FORMAT_NV21_ENCODEABLE;  // NV21
       } else {
         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) {
@@ -246,50 +239,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);
@@ -298,15 +285,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);
   }
 
@@ -325,4 +306,4 @@
 
   return;
 }
-}  // namespace gralloc1
+}  // namespace gralloc
diff --git a/gralloc/gr_allocator.h b/gralloc/gr_allocator.h
index c059ba6..2f73a0d 100644
--- a/gralloc/gr_allocator.h
+++ b/gralloc/gr_allocator.h
@@ -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 fd);
-  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
index c909fa4..932db33 100644
--- a/gralloc/gr_buf_descriptor.h
+++ b/gralloc/gr_buf_descriptor.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,34 +30,48 @@
 #ifndef __GR_BUF_DESCRIPTOR_H__
 #define __GR_BUF_DESCRIPTOR_H__
 
-#include <hardware/gralloc1.h>
+#include <android/hardware/graphics/mapper/2.0/IMapper.h>
 #include <atomic>
 
-namespace gralloc1 {
+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() : id_(next_id_++) {}
+  BufferDescriptor() {}
+  explicit BufferDescriptor(uint64_t id) : id_(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_++) {}
+  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;
+  }
 
-  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_++) {}
+  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 SetConsumerUsage(gralloc1_consumer_usage_t usage) { consumer_usage_ = usage; }
-
-  void SetProducerUsage(gralloc1_producer_usage_t usage) { producer_usage_ = usage; }
+  void SetUsage(uint64_t usage) { usage_ |= usage; }
 
   void SetDimensions(int w, int h) {
     width_ = w;
@@ -68,9 +82,7 @@
 
   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_; }
+  uint64_t GetUsage() const { return usage_; }
 
   int GetWidth() const { return width_; }
 
@@ -80,17 +92,15 @@
 
   uint32_t GetLayerCount() const { return layer_count_; }
 
-  gralloc1_buffer_descriptor_t GetId() const { return id_; }
+  uint64_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_;
+  uint64_t usage_ = 0;
+  const uint64_t id_ = 0;
 };
-};  // namespace gralloc1
+};      // namespace gralloc
 #endif  // __GR_BUF_DESCRIPTOR_H__
diff --git a/gralloc/gr_buf_mgr.cpp b/gralloc/gr_buf_mgr.cpp
index 8a1403a..95cbc75 100644
--- a/gralloc/gr_buf_mgr.cpp
+++ b/gralloc/gr_buf_mgr.cpp
@@ -20,23 +20,22 @@
 #define DEBUG 0
 
 #include <iomanip>
+#include <sstream>
 #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 "gr_priv_handle.h"
+#include "gr_utils.h"
 #include "qdMetaData.h"
+#include "qd_utils.h"
 
-namespace gralloc1 {
-std::atomic<gralloc1_buffer_descriptor_t> BufferDescriptor::next_id_(1);
+namespace gralloc {
 
 static BufferInfo GetBufferInfo(const BufferDescriptor &descriptor) {
   return BufferInfo(descriptor.GetWidth(), descriptor.GetHeight(), descriptor.GetFormat(),
-                    descriptor.GetProducerUsage(), descriptor.GetConsumerUsage());
+                    descriptor.GetUsage());
 }
 
 BufferManager::BufferManager() : next_id_(0) {
@@ -54,25 +53,9 @@
   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::GetInstance() {
+  static BufferManager *instance = new BufferManager();
+  return instance;
 }
 
 BufferManager::~BufferManager() {
@@ -81,173 +64,63 @@
   }
 }
 
-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) {
+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 GRALLOC1_ERROR_BAD_HANDLE;
+    return Error::BAD_BUFFER;
   }
 
-  if (allocator_->FreeBuffer(reinterpret_cast<void *>(hnd->base), hnd->size, hnd->offset,
-                             hnd->fd, buf->ion_handle_main) != 0) {
-    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 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 GRALLOC1_ERROR_BAD_HANDLE;
+    return Error::BAD_BUFFER;
   }
 
-  private_handle_t * handle = const_cast<private_handle_t *>(hnd);
+  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;
+    delete handle;
   }
-  return GRALLOC1_ERROR_NONE;
+  return Error::NONE;
 }
 
-void BufferManager::RegisterHandleLocked(const private_handle_t *hnd,
-                                         int ion_handle,
+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) {
+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 GRALLOC1_ERROR_BAD_HANDLE;
+    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 GRALLOC1_ERROR_BAD_HANDLE;
+    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 GRALLOC1_ERROR_NONE;
+  return Error::NONE;
 }
 
-std::shared_ptr<BufferManager::Buffer>
-BufferManager::GetBufferFromHandleLocked(const private_handle_t *hnd) {
+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;
@@ -256,21 +129,21 @@
   }
 }
 
-gralloc1_error_t BufferManager::MapBuffer(private_handle_t const *handle) {
+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 GRALLOC1_ERROR_BAD_HANDLE;
+    return Error::BAD_BUFFER;
   }
-  return GRALLOC1_ERROR_NONE;
+  return Error::NONE;
 }
 
-gralloc1_error_t BufferManager::RetainBuffer(private_handle_t const *hnd) {
+Error 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;
+  auto err = Error::NONE;
   std::lock_guard<std::mutex> lock(buffer_lock_);
   auto buf = GetBufferFromHandleLocked(hnd);
   if (buf != nullptr) {
@@ -282,13 +155,13 @@
   return err;
 }
 
-gralloc1_error_t BufferManager::ReleaseBuffer(private_handle_t const *hnd) {
+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 GRALLOC1_ERROR_BAD_HANDLE;
+    return Error::BAD_BUFFER;
   } else {
     if (buf->DecRef()) {
       handles_map_.erase(hnd);
@@ -296,24 +169,22 @@
       FreeBuffer(buf);
     }
   }
-  return GRALLOC1_ERROR_NONE;
+  return Error::NONE;
 }
 
-gralloc1_error_t BufferManager::LockBuffer(const private_handle_t *hnd,
-                                           gralloc1_producer_usage_t prod_usage,
-                                           gralloc1_consumer_usage_t cons_usage) {
+Error BufferManager::LockBuffer(const private_handle_t *hnd, uint64_t usage) {
   std::lock_guard<std::mutex> lock(buffer_lock_);
-  gralloc1_error_t err = GRALLOC1_ERROR_NONE;
+  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(prod_usage, cons_usage)) {
-    return GRALLOC1_ERROR_BAD_VALUE;
+  if (!CpuCanAccess(usage)) {
+    return Error::BAD_VALUE;
   }
 
   auto buf = GetBufferFromHandleLocked(hnd);
   if (buf == nullptr) {
-    return GRALLOC1_ERROR_BAD_HANDLE;
+    return Error::BAD_BUFFER;
   }
 
   if (hnd->base == 0) {
@@ -326,16 +197,16 @@
   // only read/written in software.
 
   // todo use handle here
-  if (!err && (hnd->flags & private_handle_t::PRIV_FLAGS_USES_ION) &&
+  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, hnd->fd)) {
-      return GRALLOC1_ERROR_BAD_HANDLE;
+      return Error::BAD_BUFFER;
     }
   }
 
   // Mark the buffer to be flushed after CPU write.
-  if (!err && CpuCanWrite(prod_usage)) {
+  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;
   }
@@ -343,20 +214,20 @@
   return err;
 }
 
-gralloc1_error_t BufferManager::UnlockBuffer(const private_handle_t *handle) {
+Error BufferManager::UnlockBuffer(const private_handle_t *handle) {
   std::lock_guard<std::mutex> lock(buffer_lock_);
-  gralloc1_error_t status = GRALLOC1_ERROR_NONE;
+  auto status = Error::NONE;
 
   private_handle_t *hnd = const_cast<private_handle_t *>(handle);
   auto buf = GetBufferFromHandleLocked(hnd);
   if (buf == nullptr) {
-    return GRALLOC1_ERROR_BAD_HANDLE;
+    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, hnd->fd) != 0) {
-      status = GRALLOC1_ERROR_BAD_HANDLE;
+      status = Error::BAD_BUFFER;
     }
     hnd->flags &= ~private_handle_t::PRIV_FLAGS_NEEDS_FLUSH;
   }
@@ -364,16 +235,14 @@
   return status;
 }
 
-uint32_t BufferManager::GetDataAlignment(int format, gralloc1_producer_usage_t prod_usage,
-                                    gralloc1_consumer_usage_t cons_usage) {
+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 (prod_usage & GRALLOC1_PRODUCER_USAGE_PROTECTED) {
-    if ((prod_usage & GRALLOC1_PRODUCER_USAGE_CAMERA) ||
-        (cons_usage & GRALLOC1_CONSUMER_USAGE_PRIVATE_SECURE_DISPLAY)) {
+  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 {
@@ -384,53 +253,46 @@
   return align;
 }
 
-int BufferManager::GetHandleFlags(int format, gralloc1_producer_usage_t prod_usage,
-                                  gralloc1_consumer_usage_t cons_usage) {
+int BufferManager::GetHandleFlags(int format, uint64_t usage) {
   int flags = 0;
-  if (cons_usage & GRALLOC1_CONSUMER_USAGE_VIDEO_ENCODER) {
+  if (usage & BufferUsage::VIDEO_ENCODER) {
     flags |= private_handle_t::PRIV_FLAGS_VIDEO_ENCODER;
   }
 
-  if (prod_usage & GRALLOC1_PRODUCER_USAGE_CAMERA) {
+  if (usage & BufferUsage::CAMERA_OUTPUT) {
     flags |= private_handle_t::PRIV_FLAGS_CAMERA_WRITE;
   }
 
-  if (prod_usage & GRALLOC1_CONSUMER_USAGE_CAMERA) {
+  if (usage & BufferUsage::CAMERA_INPUT) {
     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 (cons_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) {
+  if (usage & BufferUsage::COMPOSER_OVERLAY) {
     flags |= private_handle_t::PRIV_FLAGS_DISP_CONSUMER;
   }
 
-  if (!allocator_->UseUncached(prod_usage, cons_usage)) {
+  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;
   }
 
@@ -447,14 +309,14 @@
   return buffer_type;
 }
 
-int BufferManager::AllocateBufferLocked(const BufferDescriptor &descriptor, buffer_handle_t *handle,
-                                        unsigned int bufferSize) {
+Error BufferManager::AllocateBuffer(const BufferDescriptor &descriptor, buffer_handle_t *handle,
+                                    unsigned int bufferSize) {
   if (!handle)
-    return -EINVAL;
+    return Error::BAD_BUFFER;
+  std::lock_guard<std::mutex> buffer_lock(buffer_lock_);
 
-  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());
+  uint64_t usage = descriptor.GetUsage();
+  int format = allocator_->GetImplDefinedFormat(usage, descriptor.GetFormat());
   uint32_t layer_count = descriptor.GetLayerCount();
 
   unsigned int size;
@@ -462,6 +324,7 @@
 
   int buffer_type = GetBufferType(format);
   BufferInfo info = GetBufferInfo(descriptor);
+  info.format = format;
   GetBufferSizeAndDimensions(info, &size, &alignedw, &alignedh);
   size = (bufferSize >= size) ? bufferSize : size;
 
@@ -469,17 +332,17 @@
   int flags = 0;
   auto page_size = UINT(getpagesize());
   AllocData data;
-  data.align = GetDataAlignment(format, prod_usage, cons_usage);
+  data.align = GetDataAlignment(format, usage);
   size = ALIGN(size, data.align) * layer_count;
   data.size = size;
-  data.handle = (uintptr_t) handle;
-  data.uncached = allocator_->UseUncached(prod_usage, cons_usage);
+  data.handle = (uintptr_t)handle;
+  data.uncached = allocator_->UseUncached(usage);
 
   // Allocate buffer memory
-  err = allocator_->AllocateMem(&data, prod_usage, cons_usage);
+  err = allocator_->AllocateMem(&data, usage);
   if (err) {
     ALOGE("gralloc failed to allocate err=%s", strerror(-err));
-    return err;
+    return Error::NO_RESOURCES;
   }
 
   // Allocate memory for MetaData
@@ -488,29 +351,19 @@
   e_data.handle = data.handle;
   e_data.align = page_size;
 
-  err =
-      allocator_->AllocateMem(&e_data, GRALLOC1_PRODUCER_USAGE_NONE, GRALLOC1_CONSUMER_USAGE_NONE);
+  err = allocator_->AllocateMem(&e_data, 0);
   if (err) {
     ALOGE("gralloc failed to allocate metadata error=%s", strerror(-err));
-    return err;
+    return Error::NO_RESOURCES;
   }
 
-  flags = GetHandleFlags(format, prod_usage, cons_usage);
+  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,
-                                               prod_usage,
-                                               cons_usage);
+  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;
@@ -528,382 +381,30 @@
   if (DEBUG) {
     private_handle_t::Dump(hnd);
   }
-  return err;
+  return Error::NONE;
 }
 
-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) {
+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 << " 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;
+    *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;
+    *os << " format: "
+        << "0x" << std::setw(8) << hnd->format;
+    *os << std::dec << std::setfill(' ') << std::endl;
   }
-  return GRALLOC1_ERROR_NONE;
+  return Error::NONE;
 }
-}  //  namespace gralloc1
+}  //  namespace gralloc
diff --git a/gralloc/gr_buf_mgr.h b/gralloc/gr_buf_mgr.h
index e021afd..24b4c23 100644
--- a/gralloc/gr_buf_mgr.h
+++ b/gralloc/gr_buf_mgr.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
@@ -21,69 +21,41 @@
 #define __GR_BUF_MGR_H__
 
 #include <pthread.h>
+#include <mutex>
 #include <unordered_map>
 #include <unordered_set>
 #include <utility>
-#include <mutex>
 
-#include "gralloc_priv.h"
 #include "gr_allocator.h"
 #include "gr_buf_descriptor.h"
+#include "gralloc_priv.h"
 
-namespace gralloc1 {
+namespace gralloc {
+
+using android::hardware::graphics::mapper::V2_0::Error;
 
 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;
-  }
+  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();
-  gralloc1_error_t MapBuffer(private_handle_t const *hnd);
+  Error 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);
+  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
-  gralloc1_error_t ImportHandleLocked(private_handle_t *hnd);
+  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);
@@ -103,16 +75,13 @@
     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) {
-    }
+    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);
+  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);
@@ -120,16 +89,10 @@
   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::unordered_map<const private_handle_t *, std::shared_ptr<Buffer>> handles_map_ = {};
   std::atomic<uint64_t> next_id_;
 };
 
-}  // namespace gralloc1
+}  // namespace gralloc
 
 #endif  // __GR_BUF_MGR_H__
diff --git a/gralloc/gr_device_impl.cpp b/gralloc/gr_device_impl.cpp
index c900d23..6129bd3 100644
--- a/gralloc/gr_device_impl.cpp
+++ b/gralloc/gr_device_impl.cpp
@@ -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
@@ -29,19 +29,19 @@
 
 #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 <utils/Trace.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_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);
 
@@ -50,23 +50,25 @@
 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},
-  },
+    // 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)) {
-    gralloc1::GrallocImpl * /*gralloc1_device_t*/ dev = gralloc1::GrallocImpl::GetInstance(module);
+    gralloc::GrallocImpl * /*gralloc1_device_t*/ dev = gralloc::GrallocImpl::GetInstance(module);
     *device = reinterpret_cast<hw_device_t *>(dev);
     if (dev) {
       status = 0;
@@ -77,7 +79,9 @@
   return status;
 }
 
-namespace gralloc1 {
+namespace gralloc {
+
+std::atomic<uint64_t> GrallocImpl::next_descriptor_id_(1);
 
 GrallocImpl::GrallocImpl(const hw_module_t *module) {
   common.tag = HARDWARE_DEVICE_TAG;
@@ -87,7 +91,58 @@
   getFunction = GetFunction;
   getCapabilities = GetCapabilities;
 
-  initalized_ = Init();
+  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() {
@@ -95,7 +150,26 @@
   return buf_mgr_ != nullptr;
 }
 
-GrallocImpl::~GrallocImpl() {
+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) {
@@ -104,7 +178,7 @@
 }
 
 void GrallocImpl::GetCapabilities(struct gralloc1_device *device, uint32_t *out_count,
-                                  int32_t  /*gralloc1_capability_t*/ *out_capabilities) {
+                                  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;
@@ -216,8 +290,8 @@
   if (!device || !out_descriptor) {
     return GRALLOC1_ERROR_BAD_DESCRIPTOR;
   }
-  GrallocImpl const *dev = GRALLOC_IMPL(device);
-  return dev->buf_mgr_->CreateBufferDescriptor(out_descriptor);
+  auto *dev = reinterpret_cast<GrallocImpl *>(device);
+  return dev->CreateBufferDescriptorLocked(out_descriptor);
 }
 
 gralloc1_error_t GrallocImpl::DestroyBufferDescriptor(gralloc1_device_t *device,
@@ -225,8 +299,8 @@
   if (!device) {
     return GRALLOC1_ERROR_BAD_DESCRIPTOR;
   }
-  GrallocImpl const *dev = GRALLOC_IMPL(device);
-  return dev->buf_mgr_->DestroyBufferDescriptor(descriptor);
+  auto *dev = reinterpret_cast<GrallocImpl *>(device);
+  return dev->DestroyBufferDescriptorLocked(descriptor);
 }
 
 gralloc1_error_t GrallocImpl::SetConsumerUsage(gralloc1_device_t *device,
@@ -235,9 +309,9 @@
   if (!device) {
     return GRALLOC1_ERROR_BAD_DESCRIPTOR;
   } else {
-    GrallocImpl const *dev = GRALLOC_IMPL(device);
-    return dev->buf_mgr_->CallBufferDescriptorFunction(descriptor,
-                                                       &BufferDescriptor::SetConsumerUsage, usage);
+    auto *dev = reinterpret_cast<GrallocImpl *>(device);
+    return dev->CallBufferDescriptorFunction(descriptor, &BufferDescriptor::SetUsage,
+                                             ConsumerUsageToBufferUsage(usage));
   }
 }
 
@@ -247,10 +321,9 @@
   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));
+    auto *dev = reinterpret_cast<GrallocImpl *>(device);
+    return dev->CallBufferDescriptorFunction(descriptor, &BufferDescriptor::SetDimensions,
+                                             INT(width), INT(height));
   }
 }
 
@@ -260,9 +333,8 @@
   if (!device) {
     return GRALLOC1_ERROR_BAD_DESCRIPTOR;
   } else {
-    GrallocImpl const *dev = GRALLOC_IMPL(device);
-    return dev->buf_mgr_->CallBufferDescriptorFunction(descriptor,
-                                                       &BufferDescriptor::SetColorFormat, format);
+    auto *dev = reinterpret_cast<GrallocImpl *>(device);
+    return dev->CallBufferDescriptorFunction(descriptor, &BufferDescriptor::SetColorFormat, format);
   }
 }
 
@@ -272,10 +344,9 @@
   if (!device) {
     return GRALLOC1_ERROR_BAD_DESCRIPTOR;
   } else {
-    GrallocImpl const *dev = GRALLOC_IMPL(device);
-    return dev->buf_mgr_->CallBufferDescriptorFunction(descriptor,
-                                                       &BufferDescriptor::SetLayerCount,
-                                                       layer_count);
+    auto *dev = reinterpret_cast<GrallocImpl *>(device);
+    return dev->CallBufferDescriptorFunction(descriptor, &BufferDescriptor::SetLayerCount,
+                                             layer_count);
   }
 }
 
@@ -285,9 +356,9 @@
   if (!device) {
     return GRALLOC1_ERROR_BAD_DESCRIPTOR;
   } else {
-    GrallocImpl const *dev = GRALLOC_IMPL(device);
-    return dev->buf_mgr_->CallBufferDescriptorFunction(descriptor,
-                                                       &BufferDescriptor::SetProducerUsage, usage);
+    auto *dev = reinterpret_cast<GrallocImpl *>(device);
+    return dev->CallBufferDescriptorFunction(descriptor, &BufferDescriptor::SetUsage,
+                                             ProducerUsageToBufferUsage(usage));
   }
 }
 
@@ -307,7 +378,7 @@
                                                gralloc1_consumer_usage_t *outUsage) {
   gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
   if (status == GRALLOC1_ERROR_NONE) {
-    *outUsage = PRIV_HANDLE_CONST(buffer)->GetConsumerUsage();
+    *outUsage = static_cast<gralloc1_consumer_usage_t>(PRIV_HANDLE_CONST(buffer)->GetUsage());
   }
 
   return status;
@@ -353,8 +424,7 @@
 
   gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
   if (status == GRALLOC1_ERROR_NONE) {
-    const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
-    *outUsage = hnd->GetProducerUsage();
+    *outUsage = static_cast<gralloc1_producer_usage_t>(PRIV_HANDLE_CONST(buffer)->GetUsage());
   }
 
   return status;
@@ -374,6 +444,28 @@
   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) {
@@ -385,9 +477,12 @@
     return GRALLOC1_ERROR_BAD_VALUE;
   }
 
-  GrallocImpl const *dev = GRALLOC_IMPL(device);
-  gralloc1_error_t status = dev->buf_mgr_->AllocateBuffers(num_descriptors, descriptors,
-                                                           out_buffers);
+  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;
 }
@@ -397,7 +492,7 @@
   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);
+    status = ToError(dev->buf_mgr_->RetainBuffer(hnd));
   }
 
   return status;
@@ -410,7 +505,50 @@
 
   const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
   GrallocImpl const *dev = GRALLOC_IMPL(device);
-  return dev->buf_mgr_->ReleaseBuffer(hnd);
+  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,
@@ -421,9 +559,12 @@
 
   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);
+    if (!IsYuvFormat(hnd)) {
+      status = GRALLOC1_ERROR_UNSUPPORTED;
+    } else {
+      *out_num_planes = 3;
+    }
   }
   return status;
 }
@@ -469,8 +610,8 @@
     // 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);
+  status = ToError(dev->buf_mgr_->LockBuffer(
+      hnd, ProducerUsageToBufferUsage(prod_usage) | ConsumerUsageToBufferUsage(cons_usage)));
   *out_data = reinterpret_cast<void *>(hnd->base);
 
   return status;
@@ -487,16 +628,16 @@
     return GRALLOC1_ERROR_BAD_VALUE;
   }
 
-  void *out_data {};
+  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);
+  auto *dev = reinterpret_cast<GrallocImpl *>(device);
   const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
-  dev->buf_mgr_->GetFlexLayout(hnd, out_flex_layout);
+  dev->GetFlexLayout(hnd, out_flex_layout);
   return status;
 }
 
@@ -516,7 +657,200 @@
 
   *release_fence = -1;
 
-  return dev->buf_mgr_->UnlockBuffer(hnd);
+  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, ...) {
@@ -526,11 +860,10 @@
 
   va_list args;
   va_start(args, operation);
-  GrallocImpl const *dev = GRALLOC_IMPL(device);
-  gralloc1_error_t err = dev->buf_mgr_->Perform(operation, args);
+  gralloc1_error_t err = Perform(operation, args);
   va_end(args);
 
   return err;
 }
 
-}  // namespace gralloc1
+}  // namespace gralloc
diff --git a/gralloc/gr_device_impl.h b/gralloc/gr_device_impl.h
index 55ce44b..82e9e71 100644
--- a/gralloc/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/gralloc/gr_ion_alloc.cpp b/gralloc/gr_ion_alloc.cpp
index 4fc67f4..f327818 100644
--- a/gralloc/gr_ion_alloc.cpp
+++ b/gralloc/gr_ion_alloc.cpp
@@ -33,22 +33,22 @@
 #include <sys/mman.h>
 #include <linux/msm_ion.h>
 #if TARGET_ION_ABI_VERSION >= 2
-#include <ion/ion.h>
 #include <linux/dma-buf.h>
+#include <ion/ion.h>
 #endif
 #include <stdlib.h>
 #include <fcntl.h>
 #include <cutils/log.h>
+#include <cutils/trace.h>
 #include <errno.h>
 #include <utils/Trace.h>
-#include <cutils/trace.h>
 #include <string>
 
-#include "gralloc_priv.h"
 #include "gr_utils.h"
+#include "gralloc_priv.h"
 #include "gr_ion_alloc.h"
 
-namespace gralloc1 {
+namespace gralloc {
 
 bool IonAlloc::Init() {
   if (ion_dev_fd_ == FD_INIT) {
@@ -207,8 +207,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;
 }
@@ -342,4 +342,4 @@
   return err;
 }
 
-}  // namespace gralloc1
+}  // namespace gralloc
diff --git a/gralloc/gr_ion_alloc.h b/gralloc/gr_ion_alloc.h
index b41f5f1..763ac54 100644
--- a/gralloc/gr_ion_alloc.h
+++ b/gralloc/gr_ion_alloc.h
@@ -34,7 +34,7 @@
 
 #define FD_INIT -1
 
-namespace gralloc1 {
+namespace gralloc {
 
 enum {
   CACHE_CLEAN = 0x1,
@@ -81,6 +81,6 @@
   int ion_dev_fd_;
 };
 
-}  // namespace gralloc1
+}  // namespace gralloc
 
 #endif  // __GR_ION_ALLOC_H__
diff --git a/gralloc/gr_priv_handle.h b/gralloc/gr_priv_handle.h
index 49e09a5..c075766 100644
--- a/gralloc/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
@@ -21,8 +21,8 @@
 #define __GR_PRIV_HANDLE_H__
 
 #include <cutils/log.h>
-#include <hardware/gralloc1.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/gralloc/gr_utils.cpp b/gralloc/gr_utils.cpp
index 2eb0b11..f28699a 100644
--- a/gralloc/gr_utils.cpp
+++ b/gralloc/gr_utils.cpp
@@ -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);
   }
 
@@ -309,14 +303,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;
@@ -384,8 +378,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;
 
@@ -393,29 +386,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;
   }
 
@@ -458,8 +443,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;
@@ -495,7 +480,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;
@@ -544,8 +529,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;
@@ -554,18 +538,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;
     }
   }
@@ -684,7 +667,7 @@
   int err = 0;
 
   // This api is for RGB* formats
-  if (!gralloc1::IsUncompressedRGBFormat(hnd->format)) {
+  if (!IsUncompressedRGBFormat(hnd->format)) {
     return -EINVAL;
   }
 
@@ -714,16 +697,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)) {
@@ -816,8 +843,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;
   }
@@ -904,4 +931,4 @@
   return 0;
 }
 
-}  // namespace gralloc1
+}  // namespace gralloc
diff --git a/gralloc/gr_utils.h b/gralloc/gr_utils.h
index 7fcb6c2..eb35a6a 100644
--- a/gralloc/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/gralloc/gralloc_priv.h b/gralloc/gralloc_priv.h
index 07cc285..7f084a0 100644
--- a/gralloc/gralloc_priv.h
+++ b/gralloc/gralloc_priv.h
@@ -26,68 +26,53 @@
 
 #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
-
-/* This flag is used to indicate video NV21 format */
-#define GRALLOC1_PRODUCER_USAGE_PRIVATE_VIDEO_NV21_ENCODER (1ULL << 24)
-
-/* 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 0x02000000
+#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
+/* This flag is used to indicate video NV21 format */
+#define GRALLOC_USAGE_PRIVATE_VIDEO_NV21_ENCODER 1ULL << 48
 
-/* Unused flag */
-#define GRALLOC1_USAGE_PRIVATE_UNUSED1  0x04000000
+/* unused legacy flags */
+#define GRALLOC_USAGE_PRIVATE_MM_HEAP 0
+#define GRALLOC_USAGE_PRIVATE_IOMMU_HEAP 0
 
+/* 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
 
-/* Legacy gralloc0.x definitions */
+/* This flag is used to indicate 10-bit tight pack format (e.g. TP10) */
+#define GRALLOC_USAGE_PRIVATE_10BIT_TP 1 << 27
+
+/* 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
+#define GRALLOC1_PRODUCER_USAGE_PRIVATE_VIDEO_NV21_ENCODER GRALLOC_USAGE_PRIVATE_VIDEO_NV21_ENCODER
 
 // for PERFORM API :
 #define GRALLOC_MODULE_PERFORM_CREATE_HANDLE_FROM_BUFFER 1
@@ -139,8 +124,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
 
@@ -153,7 +138,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
@@ -190,11 +175,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..8efe313
--- /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::IQtiAllocator;
+using vendor::qti::hardware::display::allocator::V1_0::implementation::QtiAllocator;
+
+int main(int, char **) {
+  android::sp<IQtiAllocator> 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