Merge "sdm: Add support to pass HDR metadata to HDR External Displays"
diff --git a/common.mk b/common.mk
index f105330..3a55cca 100644
--- a/common.mk
+++ b/common.mk
@@ -53,6 +53,7 @@
     common_flags += -isystem $(display_top)/libgralloc
 else
     common_flags += -isystem $(display_top)/libgralloc1
+    common_flags += -DUSE_GRALLOC1
 endif
 
 ifeq ($(TARGET_USES_POST_PROCESSING),true)
diff --git a/libcopybit/Android.mk b/libcopybit/Android.mk
index a165826..3e6d8fe 100644
--- a/libcopybit/Android.mk
+++ b/libcopybit/Android.mk
@@ -21,6 +21,7 @@
 #Copy the headers regardless of whether copybit is built
 include $(BUILD_COPY_HEADERS)
 
+ifneq ($(TARGET_USES_GRALLOC1), true)
 LOCAL_MODULE                  := copybit.$(TARGET_BOARD_PLATFORM)
 LOCAL_MODULE_RELATIVE_PATH    := hw
 LOCAL_MODULE_TAGS             := optional
@@ -47,3 +48,4 @@
         endif
     endif
 endif
+endif
diff --git a/libdrmutils/drm_master.cpp b/libdrmutils/drm_master.cpp
index 9b3c48e..239ec4c 100644
--- a/libdrmutils/drm_master.cpp
+++ b/libdrmutils/drm_master.cpp
@@ -95,29 +95,31 @@
     return ret;
   }
 
-  uint32_t gem_handles[4] = {0};
-  uint32_t pitches[4] = {0};
-  uint32_t offsets[4] = {0};
-  uint64_t modifier[4] = {0};
+  struct drm_mode_fb_cmd2 cmd2 {};
+  cmd2.width = drm_buffer.width;
+  cmd2.height = drm_buffer.height;
+  cmd2.pixel_format = drm_buffer.drm_format;
+  cmd2.flags = DRM_MODE_FB_MODIFIERS;
+  fill(begin(cmd2.handles), begin(cmd2.handles) + drm_buffer.num_planes, *gem_handle);
+  copy(begin(drm_buffer.stride), end(drm_buffer.stride), begin(cmd2.pitches));
+  copy(begin(drm_buffer.offset), end(drm_buffer.offset), begin(cmd2.offsets));
+  fill(begin(cmd2.modifier), begin(cmd2.modifier) + drm_buffer.num_planes,
+       drm_buffer.drm_format_modifier);
 
-  fill(begin(gem_handles), begin(gem_handles) + drm_buffer.num_planes, *gem_handle);
-  copy(begin(drm_buffer.stride), end(drm_buffer.stride), begin(pitches));
-  copy(begin(drm_buffer.offset), end(drm_buffer.offset), begin(offsets));
-  fill(begin(modifier), begin(modifier) + drm_buffer.num_planes, drm_buffer.drm_format_modifier);
-
-  ret = drmModeAddFB3(dev_fd_, drm_buffer.width, drm_buffer.height, drm_buffer.drm_format,
-                      gem_handles, pitches, offsets, modifier, fb_id, DRM_MODE_FB_MODIFIERS);
-  if (ret) {
-    DRM_LOGE("drmModeAddFB3 failed with error %d", ret);
+  if ((ret = drmIoctl(dev_fd_, DRM_IOCTL_MODE_ADDFB2, &cmd2))) {
+    DRM_LOGE("DRM_IOCTL_MODE_ADDFB2 failed with error %d", ret);
     struct drm_gem_close gem_close = {};
     gem_close.handle = *gem_handle;
     int ret1 = drmIoctl(dev_fd_, DRM_IOCTL_GEM_CLOSE, &gem_close);
     if (ret1) {
       DRM_LOGE("drmIoctl::DRM_IOCTL_GEM_CLOSE failed with error %d", ret1);
+      return ret1;
     }
+    return ret;
   }
 
-  return ret;
+  *fb_id = cmd2.fb_id;
+  return 0;
 }
 
 int DRMMaster::RemoveFbId(uint32_t gem_handle, uint32_t fb_id) {
diff --git a/libgralloc1/gr_allocator.cpp b/libgralloc1/gr_allocator.cpp
index fefd664..3c01fbd 100644
--- a/libgralloc1/gr_allocator.cpp
+++ b/libgralloc1/gr_allocator.cpp
@@ -29,6 +29,7 @@
 
 #include <cutils/log.h>
 #include <algorithm>
+#include <vector>
 
 #include "gr_utils.h"
 #include "gr_allocator.h"
@@ -68,6 +69,9 @@
 #define ION_SC_PREVIEW_FLAGS ION_SECURE
 #endif
 
+using std::vector;
+using std::shared_ptr;
+
 namespace gralloc1 {
 
 Allocator::Allocator() : ion_allocator_(NULL), adreno_helper_(NULL) {
@@ -117,43 +121,6 @@
   return ret;
 }
 
-// Allocates buffer from width, height and format into a
-// private_handle_t. It is the responsibility of the caller
-// to free the buffer using the FreeBuffer function
-int Allocator::AllocateBuffer(const BufferDescriptor &descriptor, private_handle_t **pHnd) {
-  AllocData data;
-  unsigned int aligned_w, aligned_h;
-  data.base = 0;
-  data.fd = -1;
-  data.offset = 0;
-  data.align = (unsigned int)getpagesize();
-  int format = descriptor.GetFormat();
-  gralloc1_producer_usage_t prod_usage = descriptor.GetProducerUsage();
-  gralloc1_consumer_usage_t cons_usage = descriptor.GetConsumerUsage();
-  GetBufferSizeAndDimensions(descriptor, &data.size, &aligned_w, &aligned_h);
-
-  int err = AllocateMem(&data, prod_usage, cons_usage);
-  if (0 != err) {
-    ALOGE("%s: allocate failed", __FUNCTION__);
-    return -ENOMEM;
-  }
-
-  if (IsUBwcEnabled(format, prod_usage, cons_usage)) {
-    data.alloc_type |= private_handle_t::PRIV_FLAGS_UBWC_ALIGNED;
-  }
-
-  // Metadata is not allocated. would be empty
-  private_handle_t *hnd = new private_handle_t(
-      data.fd, data.size, INT(data.alloc_type), 0, INT(format), INT(aligned_w), INT(aligned_h), -1,
-      0, 0, descriptor.GetWidth(), descriptor.GetHeight(), prod_usage, cons_usage);
-  hnd->base = (uint64_t)data.base;
-  hnd->offset = data.offset;
-  hnd->gpuaddr = 0;
-  *pHnd = hnd;
-
-  return 0;
-}
-
 int Allocator::MapBuffer(void **base, unsigned int size, unsigned int offset, int fd) {
   if (ion_allocator_) {
     return ion_allocator_->MapBuffer(base, size, offset, fd);
@@ -162,9 +129,10 @@
   return -EINVAL;
 }
 
-int Allocator::FreeBuffer(void *base, unsigned int size, unsigned int offset, int fd) {
+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);
+    return ion_allocator_->FreeBuffer(base, size, offset, fd, handle);
   }
 
   return -EINVAL;
@@ -178,8 +146,9 @@
   return -EINVAL;
 }
 
-bool Allocator::CheckForBufferSharing(uint32_t num_descriptors, const BufferDescriptor *descriptors,
-                                      int *max_index) {
+bool Allocator::CheckForBufferSharing(uint32_t num_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;
   unsigned int cur_ion_flags = 0, prev_ion_flags = 0;
@@ -190,8 +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());
-    GetIonHeapInfo(descriptors[i].GetProducerUsage(), descriptors[i].GetConsumerUsage(),
+    cur_uncached = UseUncached(descriptors[i]->GetProducerUsage());
+    GetIonHeapInfo(descriptors[i]->GetProducerUsage(), descriptors[i]->GetConsumerUsage(),
                    &cur_heap_id, &cur_alloc_type, &cur_ion_flags);
 
     if (i > 0 && (cur_heap_id != prev_heap_id || cur_alloc_type != prev_alloc_type ||
@@ -200,8 +169,8 @@
     }
 
     // For same format type, find the descriptor with bigger size
-    GetAlignedWidthAndHeight(descriptors[i], &alignedw, &alignedh);
-    unsigned int size = GetSize(descriptors[i], alignedw, alignedh);
+    GetAlignedWidthAndHeight(*descriptors[i], &alignedw, &alignedh);
+    unsigned int size = GetSize(*descriptors[i], alignedw, alignedh);
     if (max_size < size) {
       *max_index = INT(i);
       max_size = size;
@@ -552,7 +521,7 @@
                                unsigned int *alloc_type, unsigned int *ion_flags) {
   unsigned int heap_id = 0;
   unsigned int type = 0;
-  int flags = 0;
+  unsigned int flags = 0;
   if (prod_usage & GRALLOC1_PRODUCER_USAGE_PROTECTED) {
     if (cons_usage & GRALLOC1_CONSUMER_USAGE_PRIVATE_SECURE_DISPLAY) {
       heap_id = ION_HEAP(SD_HEAP_ID);
@@ -597,7 +566,7 @@
   }
 
   *alloc_type = type;
-  *ion_flags = (unsigned int)flags;
+  *ion_flags = flags;
   *ion_heap_id = heap_id;
 
   return;
diff --git a/libgralloc1/gr_allocator.h b/libgralloc1/gr_allocator.h
index da4fbee..e73bd8c 100644
--- a/libgralloc1/gr_allocator.h
+++ b/libgralloc1/gr_allocator.h
@@ -36,6 +36,8 @@
 #define SECURE_ALIGN SZ_1M
 #endif
 
+#include <vector>
+
 #include "gralloc_priv.h"
 #include "gr_buf_descriptor.h"
 #include "gr_adreno_info.h"
@@ -48,15 +50,15 @@
   Allocator();
   ~Allocator();
   bool Init();
-  int AllocateBuffer(const BufferDescriptor &descriptor, private_handle_t **pHnd);
   int MapBuffer(void **base, unsigned int size, unsigned int offset, int fd);
-  int FreeBuffer(void *base, unsigned int size, unsigned int offset, 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 fd, int op);
   int AllocateMem(AllocData *data, gralloc1_producer_usage_t prod_usage,
                   gralloc1_consumer_usage_t cons_usage);
   // @return : index of the descriptor with maximum buffer size req
-  bool CheckForBufferSharing(uint32_t num_descriptors, const BufferDescriptor *descriptors,
-                             int *max_index);
+  bool CheckForBufferSharing(uint32_t num_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);
   unsigned int GetSize(const BufferDescriptor &d, unsigned int alignedw, unsigned int alignedh);
diff --git a/libgralloc1/gr_buf_descriptor.h b/libgralloc1/gr_buf_descriptor.h
index 1c3572d..95386fa 100644
--- a/libgralloc1/gr_buf_descriptor.h
+++ b/libgralloc1/gr_buf_descriptor.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2016-2017, The Linux Foundation. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -32,18 +32,18 @@
 
 #include <hardware/gralloc1.h>
 
-#define BUF_DESCRIPTOR(exp) reinterpret_cast<BufferDescriptor *>(exp)
-
+namespace gralloc1 {
 class BufferDescriptor {
  public:
-  BufferDescriptor() {}
+  BufferDescriptor() : id_(next_id_++) {}
 
   BufferDescriptor(int w, int h, int f)
       : width_(w),
         height_(h),
         format_(f),
         producer_usage_(GRALLOC1_PRODUCER_USAGE_NONE),
-        consumer_usage_(GRALLOC1_CONSUMER_USAGE_NONE) {}
+        consumer_usage_(GRALLOC1_CONSUMER_USAGE_NONE),
+        id_(next_id_++) {}
 
   BufferDescriptor(int w, int h, int f, gralloc1_producer_usage_t prod_usage,
                    gralloc1_consumer_usage_t cons_usage)
@@ -51,9 +51,8 @@
         height_(h),
         format_(f),
         producer_usage_(prod_usage),
-        consumer_usage_(cons_usage) {}
-
-  bool IsValid() { return (magic == kMagic); }
+        consumer_usage_(cons_usage),
+        id_(next_id_++) {}
 
   void SetConsumerUsage(gralloc1_consumer_usage_t usage) { consumer_usage_ = usage; }
 
@@ -76,15 +75,16 @@
 
   int GetFormat() const { return format_; }
 
- private:
-  static const int kMagic = 'gr1d';
+  gralloc1_buffer_descriptor_t GetId() const { return id_; }
 
-  int magic = kMagic;
+ private:
   int width_ = -1;
   int height_ = -1;
   int format_ = -1;
   gralloc1_producer_usage_t producer_usage_ = GRALLOC1_PRODUCER_USAGE_NONE;
   gralloc1_consumer_usage_t consumer_usage_ = GRALLOC1_CONSUMER_USAGE_NONE;
+  const gralloc1_buffer_descriptor_t id_;
+  static std::atomic<gralloc1_buffer_descriptor_t> next_id_;
 };
-
+};  // namespace gralloc1
 #endif  // __GR_BUF_DESCRIPTOR_H__
diff --git a/libgralloc1/gr_buf_mgr.cpp b/libgralloc1/gr_buf_mgr.cpp
index c2d8598..51166d8 100644
--- a/libgralloc1/gr_buf_mgr.cpp
+++ b/libgralloc1/gr_buf_mgr.cpp
@@ -17,10 +17,8 @@
  * limitations under the License.
  */
 
-#include <drm/drm_fourcc.h>
-#include <drm_master.h>
-
 #include <utility>
+#include <vector>
 
 #include "qd_utils.h"
 #include "gr_priv_handle.h"
@@ -30,194 +28,9 @@
 #include "qdMetaData.h"
 
 namespace gralloc1 {
+std::atomic<gralloc1_buffer_descriptor_t> BufferDescriptor::next_id_(1);
 
-using namespace drm_utils;
-
-static int getPlaneStrideOffset(private_handle_t *hnd, uint32_t *stride,
-        uint32_t *offset, uint32_t *num_planes) {
-    struct android_ycbcr yuvInfo = {};
-    *num_planes = 1;
-
-    switch (hnd->format) {
-        case HAL_PIXEL_FORMAT_RGB_565:
-        case HAL_PIXEL_FORMAT_BGR_565:
-        case HAL_PIXEL_FORMAT_RGBA_5551:
-        case HAL_PIXEL_FORMAT_RGBA_4444:
-            stride[0] = hnd->width * 2;
-            break;
-        case HAL_PIXEL_FORMAT_RGB_888:
-            stride[0] = hnd->width * 3;
-            break;
-        case HAL_PIXEL_FORMAT_RGBA_8888:
-        case HAL_PIXEL_FORMAT_BGRA_8888:
-        case HAL_PIXEL_FORMAT_RGBX_8888:
-        case HAL_PIXEL_FORMAT_BGRX_8888:
-        case HAL_PIXEL_FORMAT_RGBA_1010102:
-        case HAL_PIXEL_FORMAT_ARGB_2101010:
-        case HAL_PIXEL_FORMAT_RGBX_1010102:
-        case HAL_PIXEL_FORMAT_XRGB_2101010:
-        case HAL_PIXEL_FORMAT_BGRA_1010102:
-        case HAL_PIXEL_FORMAT_ABGR_2101010:
-        case HAL_PIXEL_FORMAT_BGRX_1010102:
-        case HAL_PIXEL_FORMAT_XBGR_2101010:
-            stride[0] = hnd->width * 4;
-            break;
-    }
-
-    // Format is RGB
-    if (stride[0]) {
-        return 0;
-    }
-
-    (*num_planes)++;
-    int ret = getYUVPlaneInfo(hnd, &yuvInfo);
-    if (ret < 0) {
-        ALOGE("%s failed", __FUNCTION__);
-        return ret;
-    }
-
-    stride[0] = static_cast<uint32_t>(yuvInfo.ystride);
-    offset[0] = static_cast<uint32_t>(
-                    reinterpret_cast<uint64_t>(yuvInfo.y) - hnd->base);
-    stride[1] = static_cast<uint32_t>(yuvInfo.cstride);
-    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:
-        case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC:
-        case HAL_PIXEL_FORMAT_YCbCr_420_P010:
-        case HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC:
-            offset[1] = static_cast<uint32_t>(
-                    reinterpret_cast<uint64_t>(yuvInfo.cb) - hnd->base);
-            break;
-        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
-        case HAL_PIXEL_FORMAT_YCrCb_420_SP_VENUS:
-        case HAL_PIXEL_FORMAT_YCrCb_422_SP:
-            offset[1] = static_cast<uint32_t>(
-                    reinterpret_cast<uint64_t>(yuvInfo.cr) - hnd->base);
-            break;
-        case HAL_PIXEL_FORMAT_YV12:
-            offset[1] = static_cast<uint32_t>(
-                    reinterpret_cast<uint64_t>(yuvInfo.cr) - hnd->base);
-            stride[2] = static_cast<uint32_t>(yuvInfo.cstride);
-            offset[2] = static_cast<uint32_t>(
-                    reinterpret_cast<uint64_t>(yuvInfo.cb) - hnd->base);
-            (*num_planes)++;
-            break;
-        default:
-            ALOGW("%s: Unsupported format %s", __FUNCTION__,
-                    qdutils::GetHALPixelFormatString(hnd->format));
-    }
-
-    if (hnd->flags & private_handle_t::PRIV_FLAGS_UBWC_ALIGNED) {
-        std::fill(offset, offset + 4, 0);
-    }
-
-    return 0;
-}
-
-static void getDRMFormat(int hal_format, int flags, uint32_t *drm_format,
-        uint64_t *drm_format_modifier) {
-
-    if (flags & private_handle_t::PRIV_FLAGS_UBWC_ALIGNED) {
-        *drm_format_modifier = DRM_FORMAT_MOD_QCOM_COMPRESSED;
-    }
-
-    switch (hal_format) {
-        case HAL_PIXEL_FORMAT_RGBA_8888:
-            *drm_format = DRM_FORMAT_RGBA8888;
-            break;
-        case HAL_PIXEL_FORMAT_RGBA_5551:
-            *drm_format = DRM_FORMAT_RGBA5551;
-            break;
-        case HAL_PIXEL_FORMAT_RGBA_4444:
-            *drm_format = DRM_FORMAT_RGBA4444;
-            break;
-        case HAL_PIXEL_FORMAT_BGRA_8888:
-            *drm_format = DRM_FORMAT_BGRA8888;
-            break;
-        case HAL_PIXEL_FORMAT_RGBX_8888:
-            *drm_format = DRM_FORMAT_RGBX8888;
-            break;
-        case HAL_PIXEL_FORMAT_BGRX_8888:
-            *drm_format = DRM_FORMAT_BGRX8888;
-            break;
-        case HAL_PIXEL_FORMAT_RGB_888:
-            *drm_format = DRM_FORMAT_RGB888;
-            break;
-        case HAL_PIXEL_FORMAT_RGB_565:
-            *drm_format = DRM_FORMAT_RGB565;
-            break;
-        case HAL_PIXEL_FORMAT_BGR_565:
-            *drm_format = DRM_FORMAT_BGR565;
-            break;
-        case HAL_PIXEL_FORMAT_RGBA_1010102:
-            *drm_format = DRM_FORMAT_RGBA1010102;
-            break;
-        case HAL_PIXEL_FORMAT_ARGB_2101010:
-            *drm_format = DRM_FORMAT_ARGB2101010;
-            break;
-        case HAL_PIXEL_FORMAT_RGBX_1010102:
-            *drm_format = DRM_FORMAT_RGBX1010102;
-            break;
-        case HAL_PIXEL_FORMAT_XRGB_2101010:
-            *drm_format = DRM_FORMAT_XRGB2101010;
-            break;
-        case HAL_PIXEL_FORMAT_BGRA_1010102:
-            *drm_format = DRM_FORMAT_BGRA1010102;
-            break;
-        case HAL_PIXEL_FORMAT_ABGR_2101010:
-            *drm_format = DRM_FORMAT_ABGR2101010;
-            break;
-        case HAL_PIXEL_FORMAT_BGRX_1010102:
-            *drm_format = DRM_FORMAT_BGRX1010102;
-            break;
-        case HAL_PIXEL_FORMAT_XBGR_2101010:
-            *drm_format = DRM_FORMAT_XBGR2101010;
-            break;
-        case HAL_PIXEL_FORMAT_YCbCr_420_SP:
-            *drm_format = DRM_FORMAT_NV12;
-            break;
-        case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:
-        case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS:
-            *drm_format = DRM_FORMAT_NV12;
-            break;
-        case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC:
-            *drm_format = DRM_FORMAT_NV12;
-            *drm_format_modifier = DRM_FORMAT_MOD_QCOM_COMPRESSED;
-            break;
-        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
-            *drm_format = DRM_FORMAT_NV21;
-            break;
-        case HAL_PIXEL_FORMAT_YCrCb_420_SP_VENUS:
-            *drm_format = DRM_FORMAT_NV21;
-            break;
-        case HAL_PIXEL_FORMAT_YCbCr_420_P010:
-            // TODO *drm_format = DRM_FORMAT_P010;
-            break;
-        case HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC:
-            // TODO *drm_format = DRM_FORMAT_P010;
-            // *drm_format_modifier = DRM_FORMAT_MOD_QCOM_COMPRESSED |
-            //        DRM_FORMAT_MOD_QCOM_TIGHT;
-            break;
-        case HAL_PIXEL_FORMAT_YCbCr_422_SP:
-            *drm_format = DRM_FORMAT_NV16;
-            break;
-        case HAL_PIXEL_FORMAT_YCrCb_422_SP:
-            *drm_format = DRM_FORMAT_NV61;
-            break;
-        case HAL_PIXEL_FORMAT_YV12:
-            *drm_format = DRM_FORMAT_YVU420;
-            break;
-        default:
-            ALOGW("%s: Unsupported format %s", __FUNCTION__,
-                    qdutils::GetHALPixelFormatString(hal_format));
-
-    }
-}
-
-BufferManager::BufferManager() {
+BufferManager::BufferManager() : next_id_(0) {
   char property[PROPERTY_VALUE_MAX];
 
   // Map framebuffer memory
@@ -235,6 +48,29 @@
   }
 
   handles_map_.clear();
+  allocator_ = new Allocator();
+  allocator_->Init();
+}
+
+
+gralloc1_error_t BufferManager::CreateBufferDescriptor(
+    gralloc1_buffer_descriptor_t *descriptor_id) {
+  std::lock_guard<std::mutex> lock(locker_);
+  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(locker_);
+  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() {
@@ -243,14 +79,8 @@
   }
 }
 
-bool BufferManager::Init() {
-  allocator_ = new Allocator();
-
-  return allocator_->Init();
-}
-
 gralloc1_error_t BufferManager::AllocateBuffers(uint32_t num_descriptors,
-                                                const BufferDescriptor *descriptors,
+                                                const gralloc1_buffer_descriptor_t *descriptor_ids,
                                                 buffer_handle_t *out_buffers) {
   bool shared = true;
   gralloc1_error_t status = GRALLOC1_ERROR_NONE;
@@ -259,10 +89,28 @@
   // client can ask to test the allocation by passing NULL out_buffers
   bool test_allocate = !out_buffers;
 
+  // Validate descriptors
+  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;
-  int max_buf_index = -1;
+  ssize_t max_buf_index = -1;
   shared = allocator_->CheckForBufferSharing(num_descriptors, descriptors, &max_buf_index);
 
   if (test_allocate) {
@@ -272,7 +120,7 @@
 
   if (shared && (max_buf_index >= 0)) {
     // Allocate one and duplicate/copy the handles for each descriptor
-    if (AllocateBuffer(descriptors[max_buf_index], &out_buffers[max_buf_index])) {
+    if (AllocateBuffer(*descriptors[UINT(max_buf_index)], &out_buffers[max_buf_index])) {
       return GRALLOC1_ERROR_NO_RESOURCES;
     }
 
@@ -281,20 +129,14 @@
       // 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]);
-
-        // since we just created handle out of existing handle add it to map
-        locker_.lock();
-        handles_map_.insert(std::pair<private_handle_t const *, int>(
-            reinterpret_cast<private_handle_t const *>(out_buffers[i]), 1));
-        locker_.unlock();
+        CreateSharedHandle(out_buffers[max_buf_index], *descriptors[i], &out_buffers[i]);
       }
     }
   } else {
     // Buffer sharing is not feasible.
-    // Allocate seperate buffer for each descriptor
+    // Allocate separate buffer for each descriptor
     for (i = 0; i < num_descriptors; i++) {
-      if (AllocateBuffer(descriptors[i], &out_buffers[i])) {
+      if (AllocateBuffer(*descriptors[i], &out_buffers[i])) {
         return GRALLOC1_ERROR_NO_RESOURCES;
       }
     }
@@ -322,46 +164,41 @@
   int buffer_type = GetBufferType(descriptor.GetFormat());
 
   // Duplicate the fds
-  private_handle_t *out_hnd = new private_handle_t(
-      dup(input->fd), input->size, flags, buffer_type, descriptor.GetFormat(), INT(alignedw),
-      INT(alignedh), dup(input->fd_metadata), input->offset_metadata, input->base_metadata,
-      descriptor.GetWidth(), descriptor.GetHeight(), descriptor.GetProducerUsage(),
-      descriptor.GetConsumerUsage());
-
   // 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
+  auto buffer = std::make_shared<Buffer>(out_hnd);
+  handles_map_.emplace(std::make_pair(out_hnd->id, buffer));
   *outbuffer = out_hnd;
 }
 
-gralloc1_error_t BufferManager::FreeBuffer(private_handle_t const *hnd) {
+gralloc1_error_t BufferManager::FreeBuffer(std::shared_ptr<Buffer> buf) {
+  auto hnd = buf->handle;
   if (allocator_->FreeBuffer(reinterpret_cast<void *>(hnd->base), hnd->size, hnd->offset,
-                             hnd->fd) != 0) {
+                             hnd->fd, buf->ion_handle_main) != 0) {
     return GRALLOC1_ERROR_BAD_HANDLE;
   }
 
   unsigned int meta_size = ALIGN((unsigned int)sizeof(MetaData_t), PAGE_SIZE);
   if (allocator_->FreeBuffer(reinterpret_cast<void *>(hnd->base_metadata), meta_size,
-                             hnd->offset_metadata, hnd->fd_metadata) != 0) {
+                             hnd->offset_metadata, hnd->fd_metadata, buf->ion_handle_meta) != 0) {
     return GRALLOC1_ERROR_BAD_HANDLE;
   }
 
-  // delete handle also
-  private_handle_t *handle = const_cast<private_handle_t *>(hnd);
-  if (handle->fb_id) {
-      int ret = DRMMaster::GetInstance(&master);
-      if (ret < 0) {
-          ALOGE("%s Failed to acquire DRMMaster instance", __FUNCTION__);
-          return ret;
-      }
-      ret = master->RemoveFbId(hnd->gem_handle, hnd->fb_id);
-      if (ret < 0) {
-          ALOGE("%s: Removing fb_id %d failed with error %d", __FUNCTION__,
-                  hnd->fb_id, errno);
-      }
-  }
-
-  delete handle;
-
+  // TODO(user): delete handle once framework bug around this is confirmed
+  // to be resolved
   return GRALLOC1_ERROR_NONE;
 }
 
@@ -385,44 +222,42 @@
 }
 
 gralloc1_error_t BufferManager::RetainBuffer(private_handle_t const *hnd) {
-  locker_.lock();
+  std::lock_guard<std::mutex> lock(locker_);
 
   // find if this handle is already in map
-  auto it = handles_map_.find(hnd);
+  auto it = handles_map_.find(hnd->id);
   if (it != handles_map_.end()) {
     // It's already in map, Just increment refcnt
     // No need to mmap the memory.
-    it->second = it->second + 1;
+    auto buf = it->second;
+    buf->ref_count++;
   } else {
     // not present in the map. mmap and then add entry to map
     if (MapBuffer(hnd) == GRALLOC1_ERROR_NONE) {
-      handles_map_.insert(std::pair<private_handle_t const *, int>(hnd, 1));
+      auto buffer = std::make_shared<Buffer>(hnd);
+      handles_map_.emplace(std::make_pair(hnd->id, buffer));
     }
   }
 
-  locker_.unlock();
   return GRALLOC1_ERROR_NONE;
 }
 
 gralloc1_error_t BufferManager::ReleaseBuffer(private_handle_t const *hnd) {
-  locker_.lock();
-
+  std::lock_guard<std::mutex> lock(locker_);
   // find if this handle is already in map
-  auto it = handles_map_.find(hnd);
+  auto it = handles_map_.find(hnd->id);
   if (it == handles_map_.end()) {
     // Corrupt handle or map.
-    locker_.unlock();
+    ALOGE("Could not find handle");
     return GRALLOC1_ERROR_BAD_HANDLE;
   } else {
-    it->second = it->second - 1;
+    auto buf = it->second;
+    buf->ref_count--;
+    if (buf->ref_count == 0) {
+      handles_map_.erase(it);
+      FreeBuffer(buf);
+    }
   }
-
-  if (!it->second) {
-    handles_map_.erase(it);
-    FreeBuffer(hnd);
-  }
-
-  locker_.unlock();
   return GRALLOC1_ERROR_NONE;
 }
 
@@ -481,9 +316,9 @@
   return status;
 }
 
-int BufferManager::GetDataAlignment(int format, gralloc1_producer_usage_t prod_usage,
+uint32_t BufferManager::GetDataAlignment(int format, gralloc1_producer_usage_t prod_usage,
                                     gralloc1_consumer_usage_t cons_usage) {
-  int align = getpagesize();
+  uint32_t align = UINT(getpagesize());
   if (format == HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED) {
     align = 8192;
   }
@@ -566,94 +401,61 @@
                                   int unaligned_h, int format, int bufferType,
                                   gralloc1_producer_usage_t prod_usage,
                                   gralloc1_consumer_usage_t cons_usage, buffer_handle_t *handle) {
+  auto page_size = UINT(getpagesize());
   int err = 0;
   int flags = 0;
-  size = ALIGN(size, PAGE_SIZE);
   AllocData data;
-  data.align = (unsigned int)GetDataAlignment(format, prod_usage, cons_usage);
-  size = ALIGN(size, data.align);
-  data.size = size;
+  data.align = GetDataAlignment(format, prod_usage, cons_usage);
+  data.size = ALIGN(size, data.align);
   data.handle = (uintptr_t)handle;
-
-  // Allocate memory
   data.uncached = allocator_->UseUncached(prod_usage);
+
+  // Allocate buffer memory
   err = allocator_->AllocateMem(&data, prod_usage, cons_usage);
   if (err) {
     ALOGE("gralloc failed to allocate err=%s", strerror(-err));
-    *handle = 0;
     return err;
   }
 
-  // allocate memory for MetaData
+  // Allocate memory for MetaData
   AllocData e_data;
-  e_data.size = ALIGN((unsigned int)sizeof(MetaData_t), PAGE_SIZE);
+  e_data.size = ALIGN(UINT(sizeof(MetaData_t)), page_size);
   e_data.handle = data.handle;
-  e_data.align = (unsigned int)getpagesize();
-
-  ColorSpace_t colorSpace = ITU_R_601;
-  if (prod_usage & GRALLOC1_PRODUCER_USAGE_CAMERA) {
-    colorSpace = ITU_R_601_FR;
-  }
+  e_data.align = page_size;
 
   err =
       allocator_->AllocateMem(&e_data, GRALLOC1_PRODUCER_USAGE_NONE, GRALLOC1_CONSUMER_USAGE_NONE);
-  ALOGE_IF(err, "gralloc failed for e_daata error=%s", strerror(-err));
+  if (err) {
+    ALOGE("gralloc failed to allocate metadata error=%s", strerror(-err));
+    return err;
+  }
 
   flags = GetHandleFlags(format, prod_usage, cons_usage);
   flags |= data.alloc_type;
 
   // Create handle
-  uint64_t eBaseAddr = (uint64_t)(e_data.base) + e_data.offset;
-  private_handle_t *hnd = new private_handle_t(data.fd, size, flags, bufferType, format, aligned_w,
-                                               aligned_h, e_data.fd, e_data.offset, eBaseAddr,
-                                               unaligned_w, unaligned_h, prod_usage, cons_usage);
+  private_handle_t *hnd = new private_handle_t(data.fd,
+                                               e_data.fd,
+                                               flags,
+                                               aligned_w,
+                                               aligned_h,
+                                               unaligned_w,
+                                               unaligned_h,
+                                               format,
+                                               bufferType,
+                                               size,
+                                               prod_usage,
+                                               cons_usage);
 
-  hnd->offset = data.offset;
-  hnd->base = (uint64_t)(data.base) + data.offset;
-  hnd->gpuaddr = 0;
+  hnd->id = ++next_id_;
+  hnd->base = reinterpret_cast<uint64_t >(data.base);
+  hnd->base_metadata = reinterpret_cast<uint64_t >(e_data.base);
 
+  ColorSpace_t colorSpace = ITU_R_601;
   setMetaData(hnd, UPDATE_COLOR_SPACE, reinterpret_cast<void *>(&colorSpace));
-  if (qdutils::getDriverType() == qdutils::DriverType::DRM &&
-          cons_usage & GRALLOC_USAGE_HW_COMPOSER) {
-      DRMBuffer buf = {};
-      int ret = getPlaneStrideOffset(hnd, buf.stride, buf.offset,
-              &buf.num_planes);
-      if (ret < 0) {
-          ALOGE("%s failed", __FUNCTION__);
-          return ret;
-      }
-
-      buf.fd = hnd->fd;
-      buf.width = hnd->width;
-      buf.height = hnd->height;
-      getDRMFormat(hnd->format, flags, &buf.drm_format,
-              &buf.drm_format_modifier);
-
-      DRMMaster *master = nullptr;
-      ret = DRMMaster::GetInstance(&master);
-      if (ret < 0) {
-          ALOGE("%s Failed to acquire DRMMaster instance", __FUNCTION__);
-          return ret;
-      }
-
-      ret = master->CreateFbId(buf, &hnd->gem_handle, &hnd->fb_id);
-      if (ret < 0) {
-          ALOGE("%s: CreateFbId failed. width %d, height %d, " \
-                  "format: %s, stride %u, error %d", __FUNCTION__,
-                  buf.width, buf.height,
-                  qdutils::GetHALPixelFormatString(hnd->format),
-                  buf.stride[0], errno);
-          return ret;
-      }
-  }
-
   *handle = hnd;
-
-  // we have just allocated the buffer & mmapped. Add to map
-  locker_.lock();
-  handles_map_.insert(std::pair<private_handle_t const *, int>(hnd, 1));
-  locker_.unlock();
-
+  auto buffer = std::make_shared<Buffer>(hnd, data.ion_handle, e_data.ion_handle);
+  handles_map_.emplace(std::make_pair(hnd->id, buffer));
   return err;
 }
 
@@ -739,8 +541,8 @@
         allocator_->GetAlignedWidthAndHeight(descriptor, &alignedw, &alignedh);
         hnd->unaligned_width = width;
         hnd->unaligned_height = height;
-        hnd->width = alignedw;
-        hnd->height = alignedh;
+        hnd->width = INT(alignedw);
+        hnd->height = INT(alignedh);
         hnd->format = format;
         *handle = reinterpret_cast<native_handle_t *>(hnd);
       }
@@ -889,11 +691,116 @@
       }
     } 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 *);
+      auto descriptor = BufferDescriptor(width, height, format, producer_usage, consumer_usage);
+      allocator_->GetBufferSizeAndDimensions(descriptor, size, aligned_width, aligned_height);
+      // Align size
+      auto align = GetDataAlignment(format, producer_usage, consumer_usage);
+      *size = ALIGN(*size, align);
+    } break;
+
+      // TODO(user): Break out similar functionality, preferably moving to a common lib.
+
+    case GRALLOC1_MODULE_PERFORM_ALLOCATE_BUFFER: {
+      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);
+      buffer_handle_t *hnd = va_arg(args, buffer_handle_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);
+      BufferDescriptor descriptor(width, height, format, producer_usage, consumer_usage);
+      unsigned int size;
+      unsigned int alignedw, alignedh;
+      allocator_->GetBufferSizeAndDimensions(descriptor, &size, &alignedw, &alignedh);
+      AllocateBuffer(descriptor, hnd, size);
+    } break;
+
     default:
       break;
   }
-
   return GRALLOC1_ERROR_NONE;
 }
 
+static 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_YCbCr_420_SP_VENUS_UBWC:
+    case HAL_PIXEL_FORMAT_YCrCb_420_SP:
+    case HAL_PIXEL_FORMAT_YCrCb_422_SP:
+    case HAL_PIXEL_FORMAT_YCrCb_420_SP_ADRENO:
+    case HAL_PIXEL_FORMAT_NV21_ZSL:
+    case HAL_PIXEL_FORMAT_RAW16:
+    case HAL_PIXEL_FORMAT_RAW10:
+    case HAL_PIXEL_FORMAT_YV12:
+      return true;
+    default:
+      return false;
+  }
+}
+
+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 ycbcr;
+  int err = allocator_->GetYUVPlaneInfo(hnd, &ycbcr);
+
+  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;
+  }
+
+  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;
+}
 }  //  namespace gralloc1
diff --git a/libgralloc1/gr_buf_mgr.h b/libgralloc1/gr_buf_mgr.h
index ed6b591..08ff2ef 100644
--- a/libgralloc1/gr_buf_mgr.h
+++ b/libgralloc1/gr_buf_mgr.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2016, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2017, The Linux Foundation. All rights reserved.
  * Not a Contribution
  *
  * Copyright (C) 2008 The Android Open Source Project
@@ -22,30 +22,55 @@
 
 #include <pthread.h>
 #include <unordered_map>
+#include <unordered_set>
+#include <utility>
 #include <mutex>
 
 #include "gralloc_priv.h"
 #include "gr_allocator.h"
+#include "gr_buf_descriptor.h"
 
 namespace gralloc1 {
 
 class BufferManager {
  public:
-  BufferManager();
   ~BufferManager();
-  bool Init();
-  gralloc1_error_t AllocateBuffers(uint32_t numDescriptors, const BufferDescriptor *descriptors,
-                                   buffer_handle_t *outBuffers);
+  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);
+
+  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(locker_);
+    const auto map_descriptor = descriptors_map_.find(descriptor_id);
+    if (map_descriptor == descriptors_map_.end()) {
+      return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+    }
+    const auto descriptor = map_descriptor->second;
+    (descriptor.get()->*member)(std::forward<Args>(args)...);
+    return GRALLOC1_ERROR_NONE;
+  }
+
+  static BufferManager* GetInstance() {
+    static BufferManager *instance = new BufferManager();
+    return instance;
+  }
 
  private:
+  BufferManager();
   gralloc1_error_t MapBuffer(private_handle_t const *hnd);
-  gralloc1_error_t FreeBuffer(private_handle_t const *hnd);
   int GetBufferType(int format);
   int AllocateBuffer(const BufferDescriptor &descriptor, buffer_handle_t *handle,
                      unsigned int bufferSize = 0);
@@ -53,18 +78,44 @@
                      int unaligned_h, int format, int bufferType,
                      gralloc1_producer_usage_t prod_usage, gralloc1_consumer_usage_t cons_usage,
                      buffer_handle_t *handle);
-  int GetDataAlignment(int format, gralloc1_producer_usage_t prod_usage,
+  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);
 
+  // Wrapper structure over private handle
+  // Values associated with the private handle
+  // that do not need to go over IPC can be placed here
+  // This structure is also not expected to be ABI stable
+  // unlike private_handle_t
+  struct Buffer {
+    const private_handle_t *handle = nullptr;
+    int ref_count = 1;
+    // Hold the main and metadata ion handles
+    // Freed from the allocator process
+    // and unused in the mapping process
+    int ion_handle_main = -1;
+    int ion_handle_meta = -1;
+
+    Buffer() = delete;
+    explicit Buffer(const private_handle_t* h, int ih_main = -1, int ih_meta = -1):
+        handle(h),
+        ion_handle_main(ih_main),
+        ion_handle_meta(ih_meta) {
+    }
+  };
+  gralloc1_error_t FreeBuffer(std::shared_ptr<Buffer> buf);
+
   bool map_fb_mem_ = false;
   bool ubwc_for_fb_ = false;
   Allocator *allocator_ = NULL;
   std::mutex locker_;
-  std::unordered_map<private_handle_t const *, int> handles_map_ = {};
+  std::unordered_map<uint64_t, std::shared_ptr<Buffer>> handles_map_ = {};
+  std::unordered_map<gralloc1_buffer_descriptor_t,
+                     std::shared_ptr<BufferDescriptor>> descriptors_map_ = {};
+  std::atomic<uint64_t> next_id_;
 };
 
 }  // namespace gralloc1
diff --git a/libgralloc1/gr_device_impl.cpp b/libgralloc1/gr_device_impl.cpp
index f837ee2..121d0cf 100644
--- a/libgralloc1/gr_device_impl.cpp
+++ b/libgralloc1/gr_device_impl.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2016-2017, The Linux Foundation. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -29,6 +29,8 @@
 
 #include <cutils/log.h>
 #include <sync/sync.h>
+#include <sstream>
+#include <string>
 
 #include "gr_device_impl.h"
 #include "gr_buf_descriptor.h"
@@ -43,13 +45,11 @@
 
 static struct hw_module_methods_t gralloc_module_methods = {.open = gralloc_device_open};
 
-struct hw_module_t gralloc_module = {};
-
-struct private_module_t HAL_MODULE_INFO_SYM = {
-  .base = {
+struct gralloc_module_t HAL_MODULE_INFO_SYM = {
+  .common = {
     .tag = HARDWARE_MODULE_TAG,
-    .version_major = 1,
-    .version_minor = 0,
+    .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",
@@ -62,42 +62,34 @@
 int gralloc_device_open(const struct hw_module_t *module, const char *name, hw_device_t **device) {
   int status = -EINVAL;
   if (!strcmp(name, GRALLOC_HARDWARE_MODULE_ID)) {
-    const private_module_t *m = reinterpret_cast<const private_module_t *>(module);
-    gralloc1::GrallocImpl * /*gralloc1_device_t*/ dev = new gralloc1::GrallocImpl(m);
+    gralloc1::GrallocImpl * /*gralloc1_device_t*/ dev = gralloc1::GrallocImpl::GetInstance(module);
     *device = reinterpret_cast<hw_device_t *>(dev);
-
     if (dev->Init()) {
       status = 0;
     } else {
       ALOGE(" Error in opening gralloc1 device");
-      return status;
     }
   }
-
   return status;
 }
 
 namespace gralloc1 {
 
-GrallocImpl::GrallocImpl(const private_module_t *module) {
+GrallocImpl::GrallocImpl(const hw_module_t *module) {
   common.tag = HARDWARE_DEVICE_TAG;
-  common.version = 1;  // TODO(user): cross check version
-  common.module = const_cast<hw_module_t *>(&module->base);
+  common.version = GRALLOC_MODULE_API_VERSION_1_0;
+  common.module = const_cast<hw_module_t *>(module);
   common.close = CloseDevice;
   getFunction = GetFunction;
   getCapabilities = GetCapabilities;
 }
 
 bool GrallocImpl::Init() {
-  buf_mgr_ = new BufferManager();
-
-  return buf_mgr_->Init();
+  buf_mgr_ = BufferManager::GetInstance();
+  return true;
 }
 
 GrallocImpl::~GrallocImpl() {
-  if (buf_mgr_) {
-    delete buf_mgr_;
-  }
 }
 
 int GrallocImpl::CloseDevice(hw_device_t *device) {
@@ -127,6 +119,8 @@
   }
 
   switch (function) {
+    case GRALLOC1_FUNCTION_DUMP:
+      return reinterpret_cast<gralloc1_function_pointer_t>(Dump);
     case GRALLOC1_FUNCTION_CREATE_DESCRIPTOR:
       return reinterpret_cast<gralloc1_function_pointer_t>(CreateBufferDescriptor);
     case GRALLOC1_FUNCTION_DESTROY_DESCRIPTOR:
@@ -157,17 +151,12 @@
       return reinterpret_cast<gralloc1_function_pointer_t>(RetainBuffer);
     case GRALLOC1_FUNCTION_RELEASE:
       return reinterpret_cast<gralloc1_function_pointer_t>(ReleaseBuffer);
-    /*  TODO(user) :definition of flex plane is not known yet
-     *  Need to implement after clarification from Google.
-    * case GRALLOC1_FUNCTION_GET_NUM_FLEX_PLANES:
-      return reinterpret_cast<gralloc1_function_pointer_t> (; */
+    case GRALLOC1_FUNCTION_GET_NUM_FLEX_PLANES:
+      return reinterpret_cast<gralloc1_function_pointer_t>(GetNumFlexPlanes);
     case GRALLOC1_FUNCTION_LOCK:
       return reinterpret_cast<gralloc1_function_pointer_t>(LockBuffer);
-    /*  TODO(user) : LOCK_YCBCR changed to LOCK_FLEX but structure is not known yet.
-     *  Need to implement after clarification from Google.
-    case GRALLOC1_PFN_LOCK_FLEX:
-      return reinterpret_cast<gralloc1_function_pointer_t> (LockYCbCrBuffer;
-    */
+    case GRALLOC1_FUNCTION_LOCK_FLEX:
+      return reinterpret_cast<gralloc1_function_pointer_t>(LockFlex);
     case GRALLOC1_FUNCTION_UNLOCK:
       return reinterpret_cast<gralloc1_function_pointer_t>(UnlockBuffer);
     case GRALLOC1_FUNCTION_PERFORM:
@@ -180,12 +169,24 @@
   return NULL;
 }
 
-gralloc1_error_t GrallocImpl::CheckDeviceAndDescriptor(gralloc1_device_t *device,
-                                                       gralloc1_buffer_descriptor_t descriptor) {
-  if (!device || !BUF_DESCRIPTOR(descriptor)->IsValid()) {
-    ALOGE("Gralloc Error : device=%p, descriptor=%p", (void *)device, (void *)descriptor);
+gralloc1_error_t GrallocImpl::Dump(gralloc1_device_t *device, uint32_t *out_size,
+                                   char *out_buffer) {
+  if (!device) {
+    ALOGE("Gralloc Error : device=%p", (void *)device);
     return GRALLOC1_ERROR_BAD_DESCRIPTOR;
   }
+  if (out_buffer == nullptr) {
+    *out_size = 1024;
+  } else {
+    std::ostringstream os;
+    // TODO(user): implement in buffer manager
+    os << "-------------------------------" << std::endl;
+    os << "QTI gralloc dump:" << std::endl;
+    os << "-------------------------------" << std::endl;
+    auto copy_size = os.str().size() < *out_size ? os.str().size() : *out_size;
+    std::copy_n(out_buffer, copy_size, os.str().begin());
+    *out_size = static_cast<uint32_t>(copy_size);
+  }
 
   return GRALLOC1_ERROR_NONE;
 }
@@ -206,69 +207,66 @@
   if (!device) {
     return GRALLOC1_ERROR_BAD_DESCRIPTOR;
   }
-
-  BufferDescriptor *descriptor = new BufferDescriptor();
-  if (descriptor == NULL) {
-    return GRALLOC1_ERROR_NO_RESOURCES;
-  }
-
-  *out_descriptor = reinterpret_cast<gralloc1_buffer_descriptor_t>(descriptor);
-
-  return GRALLOC1_ERROR_NONE;
+  GrallocImpl const *dev = GRALLOC_IMPL(device);
+  return dev->buf_mgr_->CreateBufferDescriptor(out_descriptor);
 }
 
 gralloc1_error_t GrallocImpl::DestroyBufferDescriptor(gralloc1_device_t *device,
                                                       gralloc1_buffer_descriptor_t descriptor) {
-  gralloc1_error_t status = CheckDeviceAndDescriptor(device, descriptor);
-  if (status == GRALLOC1_ERROR_NONE) {
-    delete reinterpret_cast<BufferDescriptor *>(descriptor);
+  if (!device) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
   }
-
-  return status;
+  GrallocImpl const *dev = GRALLOC_IMPL(device);
+  return dev->buf_mgr_->DestroyBufferDescriptor(descriptor);
 }
 
 gralloc1_error_t GrallocImpl::SetConsumerUsage(gralloc1_device_t *device,
                                                gralloc1_buffer_descriptor_t descriptor,
                                                gralloc1_consumer_usage_t usage) {
-  gralloc1_error_t status = CheckDeviceAndDescriptor(device, descriptor);
-  if (status == GRALLOC1_ERROR_NONE) {
-    BUF_DESCRIPTOR(descriptor)->SetConsumerUsage(usage);
+  if (!device) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  } else {
+    GrallocImpl const *dev = GRALLOC_IMPL(device);
+    return dev->buf_mgr_->CallBufferDescriptorFunction(descriptor,
+                                                       &BufferDescriptor::SetConsumerUsage, usage);
   }
-
-  return status;
 }
 
 gralloc1_error_t GrallocImpl::SetBufferDimensions(gralloc1_device_t *device,
                                                   gralloc1_buffer_descriptor_t descriptor,
                                                   uint32_t width, uint32_t height) {
-  gralloc1_error_t status = CheckDeviceAndDescriptor(device, descriptor);
-  if (status == GRALLOC1_ERROR_NONE) {
-    BUF_DESCRIPTOR(descriptor)->SetDimensions(INT(width), INT(height));
+  if (!device) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  } else {
+    GrallocImpl const *dev = GRALLOC_IMPL(device);
+    return dev->buf_mgr_->CallBufferDescriptorFunction(descriptor,
+                                                       &BufferDescriptor::SetDimensions,
+                                                       INT(width), INT(height));
   }
-
-  return status;
 }
 
 gralloc1_error_t GrallocImpl::SetColorFormat(gralloc1_device_t *device,
                                              gralloc1_buffer_descriptor_t descriptor,
                                              int32_t format) {
-  gralloc1_error_t status = CheckDeviceAndDescriptor(device, descriptor);
-  if (status == GRALLOC1_ERROR_NONE) {
-    BUF_DESCRIPTOR(descriptor)->SetColorFormat(format);
+  if (!device) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  } else {
+    GrallocImpl const *dev = GRALLOC_IMPL(device);
+    return dev->buf_mgr_->CallBufferDescriptorFunction(descriptor,
+                                                       &BufferDescriptor::SetColorFormat, format);
   }
-
-  return status;
 }
 
 gralloc1_error_t GrallocImpl::SetProducerUsage(gralloc1_device_t *device,
                                                gralloc1_buffer_descriptor_t descriptor,
                                                gralloc1_producer_usage_t usage) {
-  gralloc1_error_t status = CheckDeviceAndDescriptor(device, descriptor);
-  if (status == GRALLOC1_ERROR_NONE) {
-    BUF_DESCRIPTOR(descriptor)->SetProducerUsage(usage);
+  if (!device) {
+    return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+  } else {
+    GrallocImpl const *dev = GRALLOC_IMPL(device);
+    return dev->buf_mgr_->CallBufferDescriptorFunction(descriptor,
+                                                       &BufferDescriptor::SetProducerUsage, usage);
   }
-
-  return status;
 }
 
 gralloc1_error_t GrallocImpl::GetBackingStore(gralloc1_device_t *device, buffer_handle_t buffer,
@@ -336,16 +334,16 @@
   return status;
 }
 
-gralloc1_error_t GrallocImpl::AllocateBuffers(gralloc1_device_t *device, uint32_t num_dptors,
-                                              const gralloc1_buffer_descriptor_t *dptors,
-                                              buffer_handle_t *outBuffers) {
-  if (!num_dptors || !dptors) {
+gralloc1_error_t GrallocImpl::AllocateBuffers(gralloc1_device_t *device, uint32_t num_descriptors,
+                                              const gralloc1_buffer_descriptor_t *descriptors,
+                                              buffer_handle_t *out_buffers) {
+  if (!num_descriptors || !descriptors) {
     return GRALLOC1_ERROR_BAD_DESCRIPTOR;
   }
 
   GrallocImpl const *dev = GRALLOC_IMPL(device);
-  const BufferDescriptor *descriptors = reinterpret_cast<const BufferDescriptor *>(dptors);
-  gralloc1_error_t status = dev->buf_mgr_->AllocateBuffers(num_dptors, descriptors, outBuffers);
+  gralloc1_error_t status = dev->buf_mgr_->AllocateBuffers(num_descriptors, descriptors,
+                                                           out_buffers);
 
   return status;
 }
@@ -372,6 +370,17 @@
   return status;
 }
 
+gralloc1_error_t GrallocImpl::GetNumFlexPlanes(gralloc1_device_t *device, buffer_handle_t buffer,
+                                               uint32_t *out_num_planes) {
+  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
+  if (status == GRALLOC1_ERROR_NONE) {
+    GrallocImpl const *dev = GRALLOC_IMPL(device);
+    const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
+    status = dev->buf_mgr_->GetNumFlexPlanes(hnd, out_num_planes);
+  }
+  return status;
+}
+
 gralloc1_error_t GrallocImpl::LockBuffer(gralloc1_device_t *device, buffer_handle_t buffer,
                                          gralloc1_producer_usage_t prod_usage,
                                          gralloc1_consumer_usage_t cons_usage,
@@ -392,14 +401,16 @@
   // Either producer usage or consumer usage must be *_USAGE_NONE
   if ((prod_usage != GRALLOC1_PRODUCER_USAGE_NONE) &&
       (cons_usage != GRALLOC1_CONSUMER_USAGE_NONE)) {
-    return GRALLOC1_ERROR_BAD_VALUE;
+    // Current gralloc1 clients do not satisfy this restriction.
+    // See b/33588773 for details
+    // return GRALLOC1_ERROR_BAD_VALUE;
   }
 
   // currently we ignore the region/rect client wants to lock
   if (region == NULL) {
     return GRALLOC1_ERROR_BAD_VALUE;
   }
-
+  // TODO(user): Need to check if buffer was allocated with the same flags
   status = dev->buf_mgr_->LockBuffer(hnd, prod_usage, cons_usage);
 
   *out_data = reinterpret_cast<void *>(hnd->base);
@@ -407,27 +418,24 @@
   return status;
 }
 
-/*  TODO(user) : LOCK_YCBCR changed to LOCK_FLEX but structure definition is not known yet.
- *  Need to implement after clarification from Google.
-gralloc1_error_t GrallocImpl::LockYCbCrBuffer(gralloc1_device_t* device, buffer_handle_t buffer,
-    gralloc1_producer_usage_t prod_usage, gralloc1_consumer_usage_t cons_usage,
-    const gralloc1_rect_t* region, struct android_ycbcr* outYCbCr, int32_t* outAcquireFence) {
-  gralloc1_error_t status = CheckDeviceAndHandle(device, buffer);
-
-  if (status == GRALLOC1_ERROR_NONE) {
-    void **outData = 0;
-    status = LockBuffer(device, buffer, prod_usage, cons_usage, region, outData, outAcquireFence);
+gralloc1_error_t GrallocImpl::LockFlex(gralloc1_device_t *device, buffer_handle_t buffer,
+                                       gralloc1_producer_usage_t prod_usage,
+                                       gralloc1_consumer_usage_t cons_usage,
+                                       const gralloc1_rect_t *region,
+                                       struct android_flex_layout *out_flex_layout,
+                                       int32_t acquire_fence) {
+  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;
   }
 
-  if (status == GRALLOC1_ERROR_NONE) {
-    const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
-    GrallocImpl const *dev = GRALLOC_IMPL(device);
-    dev->allocator_->GetYUVPlaneInfo(hnd, outYCbCr);
-  }
-
+  GrallocImpl const *dev = GRALLOC_IMPL(device);
+  const private_handle_t *hnd = PRIV_HANDLE_CONST(buffer);
+  dev->buf_mgr_->GetFlexLayout(hnd, out_flex_layout);
   return status;
 }
- */
 
 gralloc1_error_t GrallocImpl::UnlockBuffer(gralloc1_device_t *device, buffer_handle_t buffer,
                                            int32_t *release_fence) {
diff --git a/libgralloc1/gr_device_impl.h b/libgralloc1/gr_device_impl.h
index 4fc8e3c..80c3182 100644
--- a/libgralloc1/gr_device_impl.h
+++ b/libgralloc1/gr_device_impl.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2016-2017, The Linux Foundation. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -44,7 +44,6 @@
 
 class GrallocImpl : public gralloc1_device_t {
  public:
-  explicit GrallocImpl(const private_module_t *module);
   ~GrallocImpl();
   bool Init();
   static int CloseDevice(hw_device_t *device);
@@ -53,9 +52,14 @@
   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 *instance = new GrallocImpl(module);
+    return instance;
+  }
+
  private:
-  static inline gralloc1_error_t CheckDeviceAndDescriptor(gralloc1_device_t *device,
-                                                          gralloc1_buffer_descriptor_t descriptor);
+  static inline gralloc1_error_t Dump(gralloc1_device_t *device, uint32_t *out_size,
+                                      char *out_buffer);
   static inline gralloc1_error_t CheckDeviceAndHandle(gralloc1_device_t *device,
                                                       buffer_handle_t buffer);
   static gralloc1_error_t CreateBufferDescriptor(gralloc1_device_t *device,
@@ -90,29 +94,25 @@
                                           buffer_handle_t *out_buffers);
   static gralloc1_error_t RetainBuffer(gralloc1_device_t *device, buffer_handle_t buffer);
   static gralloc1_error_t ReleaseBuffer(gralloc1_device_t *device, buffer_handle_t buffer);
-  static gralloc1_error_t getNumFlexPlanes(gralloc1_device_t *device, buffer_handle_t buffer,
+  static gralloc1_error_t GetNumFlexPlanes(gralloc1_device_t *device, buffer_handle_t buffer,
                                            uint32_t *out_num_planes);
   static gralloc1_error_t LockBuffer(gralloc1_device_t *device, buffer_handle_t buffer,
                                      gralloc1_producer_usage_t prod_usage,
                                      gralloc1_consumer_usage_t cons_usage,
-                                     const gralloc1_rect_t *access_region, void **out_data,
+                                     const gralloc1_rect_t *region, void **out_data,
                                      int32_t acquire_fence);
   static gralloc1_error_t LockFlex(gralloc1_device_t *device, buffer_handle_t buffer,
                                    gralloc1_producer_usage_t prod_usage,
                                    gralloc1_consumer_usage_t cons_usage,
-                                   const gralloc1_rect_t *access_region,
+                                   const gralloc1_rect_t *region,
                                    struct android_flex_layout *out_flex_layout,
-                                   int32_t acquireFence);
-  /*  TODO(user) : LOCK_YCBCR changed to LOCK_FLEX but structure is not known yet.
-   *  Need to implement after clarification from Google.
-  static gralloc1_error_t LockYCbCrBuffer(gralloc1_device_t* device, buffer_handle_t buffer,
-      gralloc1_producer_usage_t producerUsage, gralloc1_consumer_usage_t consumerUsage,
-      const gralloc1_rect_t* Region, struct android_ycbcr* outYCbCr, int32_t* outAcquireFence);
-   */
+                                   int32_t acquire_fence);
+
   static gralloc1_error_t UnlockBuffer(gralloc1_device_t *device, buffer_handle_t buffer,
                                        int32_t *release_fence);
   static gralloc1_error_t Gralloc1Perform(gralloc1_device_t *device, int operation, ...);
 
+  explicit GrallocImpl(const hw_module_t *module);
   BufferManager *buf_mgr_ = NULL;
 };
 
diff --git a/libgralloc1/gr_ion_alloc.cpp b/libgralloc1/gr_ion_alloc.cpp
index ca93a63..b76fa9f 100644
--- a/libgralloc1/gr_ion_alloc.cpp
+++ b/libgralloc1/gr_ion_alloc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2015, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2017, The Linux Foundation. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -106,21 +106,26 @@
 
   data->base = base;
   data->fd = fd_data.fd;
-  ioctl(ion_dev_fd_, INT(ION_IOC_FREE), &handle_data);
-  ALOGD_IF(DEBUG, "ion: Allocated buffer base:%p size:%zu fd:%d", data->base, ion_alloc_data.len,
-           data->fd);
+  data->ion_handle = handle_data.handle;
+  ALOGD_IF(DEBUG, "ion: Allocated buffer base:%p size:%zu fd:%d handle:0x%x", data->base,
+           ion_alloc_data.len, data->fd, data->ion_handle);
 
   return 0;
 }
 
-int IonAlloc::FreeBuffer(void *base, unsigned int size, unsigned int offset, int fd) {
+int IonAlloc::FreeBuffer(void *base, unsigned int size, unsigned int offset, int fd,
+                         int ion_handle) {
   ATRACE_CALL();
   int err = 0;
-  ALOGD_IF(DEBUG, "ion: Freeing buffer base:%p size:%u fd:%d", base, size, fd);
+  ALOGD_IF(DEBUG, "ion: Freeing buffer base:%p size:%u fd:%d handle:0x%x", base, size, fd,
+           ion_handle);
 
   if (base) {
     err = UnmapBuffer(base, size, offset);
   }
+  struct ion_handle_data handle_data;
+  handle_data.handle = ion_handle;
+  ioctl(ion_dev_fd_, INT(ION_IOC_FREE), &handle_data);
   close(fd);
 
   return err;
diff --git a/libgralloc1/gr_ion_alloc.h b/libgralloc1/gr_ion_alloc.h
index baef8aa..68f453c 100644
--- a/libgralloc1/gr_ion_alloc.h
+++ b/libgralloc1/gr_ion_alloc.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2015, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2017, The Linux Foundation. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -45,6 +45,7 @@
 struct AllocData {
   void *base = NULL;
   int fd = -1;
+  int ion_handle = -1;
   unsigned int offset = 0;
   unsigned int size = 0;
   unsigned int align = 1;
@@ -63,7 +64,7 @@
 
   bool Init();
   int AllocBuffer(AllocData *data);
-  int FreeBuffer(void *base, unsigned int size, unsigned int offset, int fd);
+  int FreeBuffer(void *base, unsigned int size, unsigned int offset, int fd, int ion_handle);
   int MapBuffer(void **base, unsigned int size, unsigned int offset, int fd);
   int UnmapBuffer(void *base, unsigned int size, unsigned int offset);
   int CleanBuffer(void *base, unsigned int size, unsigned int offset, int fd, int op);
diff --git a/libgralloc1/gr_priv_handle.h b/libgralloc1/gr_priv_handle.h
index 8a01d38..61190c2 100644
--- a/libgralloc1/gr_priv_handle.h
+++ b/libgralloc1/gr_priv_handle.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2016, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2017, The Linux Foundation. All rights reserved.
  * Not a Contribution
  *
  * Copyright (C) 2008 The Android Open Source Project
@@ -22,6 +22,7 @@
 
 #include <cutils/log.h>
 #include <hardware/gralloc1.h>
+#include <hardware/gralloc.h>
 
 #define GRALLOC1_FUNCTION_PERFORM 0x00001000
 
@@ -29,20 +30,15 @@
 
 typedef gralloc1_error_t (*GRALLOC1_PFN_PERFORM)(gralloc1_device_t *device, int operation, ...);
 
-typedef int BackStoreFd;
-
 #define PRIV_HANDLE_CONST(exp) static_cast<const private_handle_t *>(exp)
 
 struct private_handle_t : public native_handle_t {
-  // TODO(user): Moving PRIV_FLAGS to #defs & check for each PRIV_FLAG and remove unused.
   enum {
     PRIV_FLAGS_FRAMEBUFFER = 0x00000001,
     PRIV_FLAGS_USES_ION = 0x00000008,
-    PRIV_FLAGS_USES_ASHMEM = 0x00000010,
     PRIV_FLAGS_NEEDS_FLUSH = 0x00000020,
     PRIV_FLAGS_INTERNAL_ONLY = 0x00000040,
     PRIV_FLAGS_NON_CPU_WRITER = 0x00000080,
-    PRIV_FLAGS_NONCONTIGUOUS_MEM = 0x00000100,
     PRIV_FLAGS_CACHED = 0x00000200,
     PRIV_FLAGS_SECURE_BUFFER = 0x00000400,
     PRIV_FLAGS_EXTERNAL_ONLY = 0x00002000,
@@ -59,36 +55,31 @@
     PRIV_FLAGS_TILE_RENDERED = 0x02000000,
     PRIV_FLAGS_CPU_RENDERED = 0x04000000,
     PRIV_FLAGS_UBWC_ALIGNED = 0x08000000,
-    PRIV_FLAGS_DISP_CONSUMER = 0x10000000
+    PRIV_FLAGS_DISP_CONSUMER = 0x10000000,
+    PRIV_FLAGS_CLIENT_ALLOCATED = 0x20000000,   // Ion buffer allocated outside of gralloc
   };
 
-  // file-descriptors
+  // file-descriptors dup'd over IPC
   int fd;
   int fd_metadata;
 
-  // ints
+  // values sent over IPC
   int magic;
   int flags;
-  unsigned int size;
-  unsigned int offset;
-  int buffer_type;
-  uint64_t base __attribute__((aligned(8)));
-  unsigned int offset_metadata;
-
-  // The gpu address mapped into the mmu.
-  uint64_t gpuaddr __attribute__((aligned(8)));
-
-  int format;
-  int width;   // holds width of the actual buffer allocated
-  int height;  // holds height of the  actual buffer allocated
-
-  int stride;
-  uint64_t base_metadata __attribute__((aligned(8)));
-  unsigned int fb_id;
-
-  // added for gralloc1
+  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 size;
+  unsigned int offset;
+  unsigned int offset_metadata;
+  unsigned int fb_id;
+  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)));
 
@@ -96,58 +87,57 @@
   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, unsigned int size, int flags, int buf_type, int format, int width,
-                   int height)
+  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)
       : fd(fd),
-        fd_metadata(-1),
+        fd_metadata(meta_fd),
         magic(kMagic),
         flags(flags),
-        size(size),
-        offset(0),
-        buffer_type(buf_type),
-        base(0),
-        offset_metadata(0),
-        gpuaddr(0),
-        format(format),
         width(width),
         height(height),
+        unaligned_width(uw),
+        unaligned_height(uh),
+        format(format),
+        buffer_type(buf_type),
+        size(size),
+        offset(0),
+        offset_metadata(0),
+        fb_id(0),
+        base(0),
         base_metadata(0),
-        unaligned_width(width),
-        unaligned_height(height),
-        producer_usage(GRALLOC1_PRODUCER_USAGE_NONE),
-        consumer_usage(GRALLOC1_CONSUMER_USAGE_NONE),
-        fb_id(0) {
+        gpuaddr(0),
+        id(0),
+        producer_usage(prod_usage),
+        consumer_usage(cons_usage) {
     version = static_cast<int>(sizeof(native_handle));
     numInts = NumInts();
     numFds = kNumFds;
   }
 
-  private_handle_t(int fd, unsigned int size, int flags, int buf_type, int format, int width,
-                   int height, int meta_fd, unsigned int meta_offset, uint64_t meta_base)
-      : private_handle_t(fd, size, flags, buf_type, format, width, height) {
-    fd_metadata = meta_fd;
-    offset_metadata = meta_offset;
-    base_metadata = meta_base;
-  }
-
-  private_handle_t(int fd, unsigned int size, int flags, int buf_type, int format, int width,
-                   int height, int meta_fd, unsigned int meta_offset, uint64_t meta_base,
-                   int unaligned_w , int unaligned_h,
-                   gralloc1_producer_usage_t prod_usage, gralloc1_consumer_usage_t cons_usage)
-      : private_handle_t(fd, size, flags, buf_type, format, width, height, meta_fd, meta_offset
-                         meta_base) {
-    unaligned_width = unaligned_w;
-    unaligned_height = unaligned_h;
-    producer_usage = prod_usage;
-    consumer_usage = cons_usage;
+// 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() {
     magic = 0;
-    ALOGE_IF(DBG_HANDLE, "deleting buffer handle %p", this);
+    ALOGE_IF(DBG_HANDLE, "Deleting buffer handle %p", this);
   }
 
   static int validate(const native_handle *h) {
@@ -177,8 +167,7 @@
   int GetColorFormat() const { return format; }
 
   int GetStride() const {
-    // In handle we are storing aligned width after allocation.
-    // Why GetWidth & GetStride?? Are we supposed to maintain unaligned values??
+    // In handle we currently store aligned width after allocation.
     return width;
   }
 
@@ -186,7 +175,7 @@
 
   gralloc1_producer_usage_t GetProducerUsage() const { return producer_usage; }
 
-  BackStoreFd GetBackingstore() const { return fd; }
+  int GetBackingstore() const { return fd; }
 };
 
 #endif  // __GR_PRIV_HANDLE_H__
diff --git a/libgralloc1/gralloc_priv.h b/libgralloc1/gralloc_priv.h
index 0695a60..fa04b1b 100644
--- a/libgralloc1/gralloc_priv.h
+++ b/libgralloc1/gralloc_priv.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2016, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2017, The Linux Foundation. All rights reserved.
  * Not a Contribution
  *
  * Copyright (C) 2008 The Android Open Source Project
@@ -24,50 +24,64 @@
 #include "gr_priv_handle.h"
 
 #define ROUND_UP_PAGESIZE(x) roundUpToPageSize(x)
-inline unsigned int roundUpToPageSize(unsigned int x) {
+inline int roundUpToPageSize(int x) {
     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 */
 
-/* GRALLOC_USAGE_PRIVATE_0 is unused */
-
+/* Producer flags */
 /* Non linear, Universal Bandwidth Compression */
-#define GRALLOC1_PRODUCER_USAGE_PRIVATE_ALLOC_UBWC GRALLOC1_PRODUCER_USAGE_PRIVATE_1
-
-/* 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_2
-
-/* MM heap is a carveout heap for video, can be secured */
-#define GRALLOC1_PRODUCER_USAGE_PRIVATE_MM_HEAP GRALLOC1_PRODUCER_USAGE_PRIVATE_3
-
-/* ADSP heap is a carveout heap, is not secured */
-#define GRALLOC1_PRODUCER_USAGE_PRIVATE_ADSP_HEAP GRALLOC1_PRODUCER_USAGE_PRIVATE_4
-
-/* CAMERA heap is a carveout heap for camera, is not secured */
-#define GRALLOC1_PRODUCER_USAGE_PRIVATE_CAMERA_HEAP GRALLOC1_PRODUCER_USAGE_PRIVATE_5
+#define GRALLOC1_PRODUCER_USAGE_PRIVATE_ALLOC_UBWC  GRALLOC1_PRODUCER_USAGE_PRIVATE_0
 
 /* 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_6
+#define GRALLOC1_PRODUCER_USAGE_PRIVATE_UNCACHED    GRALLOC1_PRODUCER_USAGE_PRIVATE_1
 
-#define GRALLOC1_PRODUCER_USAGE_PRIVATE_CAMERA_ZSL GRALLOC1_PRODUCER_USAGE_PRIVATE_7
+/* CAMERA heap is a carveout heap for camera, is not secured */
+#define GRALLOC1_PRODUCER_USAGE_PRIVATE_CAMERA_HEAP GRALLOC1_PRODUCER_USAGE_PRIVATE_2
 
-/* Buffer content should be displayed on a primary display only */
-#define GRALLOC1_CONSUMER_USAGE_PRIVATE_INTERNAL_ONLY GRALLOC1_CONSUMER_USAGE_PRIVATE_1
+/* ADSP heap is a carveout heap, is not secured */
+#define GRALLOC1_PRODUCER_USAGE_PRIVATE_ADSP_HEAP   GRALLOC1_PRODUCER_USAGE_PRIVATE_3
 
-/* Buffer content should be displayed on an external display only */
-#define GRALLOC1_CONSUMER_USAGE_PRIVATE_EXTERNAL_ONLY GRALLOC1_CONSUMER_USAGE_PRIVATE_2
+/* 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
+
+
+/* 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 GRALLOC1_CONSUMER_USAGE_PRIVATE_3
+#define GRALLOC1_CONSUMER_USAGE_PRIVATE_WFD            0x00200000
 
 /* This flag is used for SECURE display usecase */
-#define GRALLOC1_CONSUMER_USAGE_PRIVATE_SECURE_DISPLAY GRALLOC1_CONSUMER_USAGE_PRIVATE_4
+#define GRALLOC1_CONSUMER_USAGE_PRIVATE_SECURE_DISPLAY 0x00800000
+
+/* Buffer content should be displayed on a primary display only */
+#define GRALLOC1_CONSUMER_USAGE_PRIVATE_INTERNAL_ONLY  0x04000000
+
+/* Buffer content should be displayed on an external display only */
+#define GRALLOC1_CONSUMER_USAGE_PRIVATE_EXTERNAL_ONLY  0x08000000
+
+
+/* Legacy gralloc0.x 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_CAMERA_HEAP GRALLOC1_PRODUCER_USAGE_PRIVATE_CAMERA_HEAP
+#define GRALLOC_USAGE_PRIVATE_MM_HEAP 0x0
+
+
 
 // for PERFORM API :
-// TODO(user): Move it to enum if it's ookay for gfx
 #define GRALLOC_MODULE_PERFORM_CREATE_HANDLE_FROM_BUFFER 1
 #define GRALLOC_MODULE_PERFORM_GET_STRIDE 2
 #define GRALLOC_MODULE_PERFORM_GET_CUSTOM_STRIDE_FROM_HANDLE 3
@@ -81,6 +95,8 @@
 #define GRALLOC_MODULE_PERFORM_GET_IGC 11
 #define GRALLOC_MODULE_PERFORM_SET_IGC 12
 #define GRALLOC_MODULE_PERFORM_SET_SINGLE_BUFFER_MODE 13
+#define GRALLOC1_MODULE_PERFORM_GET_BUFFER_SIZE_AND_DIMENSIONS 14
+#define GRALLOC1_MODULE_PERFORM_ALLOCATE_BUFFER 15
 
 // OEM specific HAL formats
 #define HAL_PIXEL_FORMAT_RGBA_5551 6
diff --git a/sdm/include/private/extension_interface.h b/sdm/include/private/extension_interface.h
index c5e6dcb..a10a2c8 100644
--- a/sdm/include/private/extension_interface.h
+++ b/sdm/include/private/extension_interface.h
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2015 - 2016, The Linux Foundation. All rights reserved.
+* Copyright (c) 2015 - 2017, The Linux Foundation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted
 * provided that the following conditions are met:
@@ -56,6 +56,7 @@
                                            const HWPanelInfo &hw_panel_info,
                                            const HWMixerAttributes &mixer_attributes,
                                            const HWDisplayAttributes &display_attributes,
+                                           const DisplayConfigVariableInfo &fb_config,
                                            PartialUpdateInterface **interface) = 0;
   virtual DisplayError DestroyPartialUpdate(PartialUpdateInterface *interface) = 0;
 
diff --git a/sdm/include/private/hw_info_types.h b/sdm/include/private/hw_info_types.h
index 6ed90ae..34c92df 100644
--- a/sdm/include/private/hw_info_types.h
+++ b/sdm/include/private/hw_info_types.h
@@ -413,6 +413,7 @@
   uint32_t mixer_height = 0;
   bool scale_update = false;
   HWScaleData scale_data = {};
+  LayerRect panel_roi = {};
 };
 
 typedef std::map<uint32_t, HWDestScaleInfo *> DestScaleInfoMap;
@@ -464,14 +465,15 @@
 
   std::vector<Layer> hw_layers = {};  // Layers which need to be programmed on the HW
 
-  uint32_t index[kMaxSDELayers];   // Indexes of the layers from the layer stack which need to be
-                                   // programmed on hardware.
+  uint32_t index[kMaxSDELayers] = {};   // Indexes of the layers from the layer stack which need to
+                                        // be programmed on hardware.
   uint32_t roi_index[kMaxSDELayers] = {0};  // Stores the ROI index where the layers are visible.
 
   int sync_handle = -1;
 
-  std::vector<LayerRect> left_frame_roi;   // Left ROI.
-  std::vector<LayerRect> right_frame_roi;  // Right ROI.
+  std::vector<LayerRect> left_frame_roi = {};   // Left ROI.
+  std::vector<LayerRect> right_frame_roi = {};  // Right ROI.
+  LayerRect partial_fb_roi = {};   // Damaged area in framebuffer.
 
   bool roi_split = false;          // Indicates separated left and right ROI
 
diff --git a/sdm/libs/core/display_base.cpp b/sdm/libs/core/display_base.cpp
index 64cebc1..3378559 100644
--- a/sdm/libs/core/display_base.cpp
+++ b/sdm/libs/core/display_base.cpp
@@ -59,11 +59,13 @@
   fb_config_ = display_attributes_;
 
   error = Debug::GetMixerResolution(&mixer_attributes_.width, &mixer_attributes_.height);
+  if (error == kErrorNone) {
+    hw_intf_->SetMixerAttributes(mixer_attributes_);
+  }
+
+  error = hw_intf_->GetMixerAttributes(&mixer_attributes_);
   if (error != kErrorNone) {
-    error = hw_intf_->GetMixerAttributes(&mixer_attributes_);
-    if (error != kErrorNone) {
-      return error;
-    }
+    return error;
   }
 
   // Override x_pixels and y_pixels of frame buffer with mixer width and height
@@ -558,6 +560,12 @@
     }
   }
 
+  LayerRect &fb_roi = layer_info.partial_fb_roi;
+  if (IsValid(fb_roi)) {
+    DumpImpl::AppendString(buffer, length, "\nPartial FB ROI(L T R B) : (%d %d %d %d)",
+                          INT(fb_roi.left), INT(fb_roi.top), INT(fb_roi.right), INT(fb_roi.bottom));
+  }
+
   const char *header  = "\n| Idx |  Comp Type  |  Split | WB |  Pipe  |    W x H    |          Format          |  Src Rect (L T R B) |  Dst Rect (L T R B) |  Z |    Flags   | Deci(HxV) | CS | Rng |";  //NOLINT
   const char *newline = "\n|-----|-------------|--------|----|--------|-------------|--------------------------|---------------------|---------------------|----|------------|-----------|----|-----|";  //NOLINT
   const char *format  = "\n| %3s | %11s "     "| %6s " "| %2s | 0x%04x | %4d x %4d | %24s "                  "| %4d %4d %4d %4d "  "| %4d %4d %4d %4d "  "| %2s | %10s "   "| %9s | %2s | %3s |";  //NOLINT
diff --git a/sdm/libs/core/display_virtual.cpp b/sdm/libs/core/display_virtual.cpp
index 04922c4..6baa3ed 100644
--- a/sdm/libs/core/display_virtual.cpp
+++ b/sdm/libs/core/display_virtual.cpp
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2014 - 2016, The Linux Foundation. All rights reserved.
+* Copyright (c) 2014 - 2017, The Linux Foundation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted
 * provided that the following conditions are met:
@@ -86,7 +86,6 @@
   DisplayError error = kErrorNone;
   HWDisplayAttributes display_attributes;
   HWMixerAttributes mixer_attributes;
-  DisplayConfigVariableInfo fb_config = *variable_info;
 
   display_attributes.x_pixels = variable_info->x_pixels;
   display_attributes.y_pixels = variable_info->y_pixels;
@@ -106,10 +105,6 @@
     return error;
   }
 
-  // Override x_pixels and y_pixels of frame buffer with mixer width and height
-  fb_config.x_pixels = mixer_attributes.width;
-  fb_config.y_pixels = mixer_attributes.height;
-
   // if display is already connected, unregister display from composition manager and register
   // the display with new configuration.
   if (display_comp_ctx_) {
@@ -117,14 +112,16 @@
   }
 
   error = comp_manager_->RegisterDisplay(display_type_, display_attributes, hw_panel_info_,
-                                         mixer_attributes, fb_config, &display_comp_ctx_);
+                                         mixer_attributes, fb_config_, &display_comp_ctx_);
   if (error != kErrorNone) {
     return error;
   }
 
   display_attributes_ = display_attributes;
   mixer_attributes_ = mixer_attributes;
-  fb_config_ = fb_config;
+
+  DLOGI("Virtual display resolution changed to[%dx%d]", display_attributes_.x_pixels,
+        display_attributes_.y_pixels);
 
   return kErrorNone;
 }
diff --git a/sdm/libs/core/fb/hw_device.cpp b/sdm/libs/core/fb/hw_device.cpp
index 10ff6fb..999265e 100644
--- a/sdm/libs/core/fb/hw_device.cpp
+++ b/sdm/libs/core/fb/hw_device.cpp
@@ -327,6 +327,10 @@
     dest_scalar_data->dest_scaler_ndx = i;
     dest_scalar_data->lm_width = dest_scale_info->mixer_width;
     dest_scalar_data->lm_height = dest_scale_info->mixer_height;
+#ifdef MDP_DESTSCALER_ROI_ENABLE
+    SetRect(dest_scale_info->panel_roi, &dest_scalar_data->panel_roi);
+    dest_scalar_data->flags |= MDP_DESTSCALER_ROI_ENABLE;
+#endif
     dest_scalar_data->scale = reinterpret_cast <uint64_t>
       (hw_scale_->GetScaleDataRef(index, kHWDestinationScalar));
 
@@ -336,6 +340,11 @@
              dest_scalar_data->dest_scaler_ndx);
     DLOGV_IF(kTagDriverConfig, "Mixer WxH %dx%d flags %x", dest_scalar_data->lm_width,
              dest_scalar_data->lm_height, dest_scalar_data->flags);
+#ifdef MDP_DESTSCALER_ROI_ENABLE
+    DLOGV_IF(kTagDriverConfig, "Panel ROI [%d, %d, %d, %d]", dest_scalar_data->panel_roi.x,
+             dest_scalar_data->panel_roi.y, dest_scalar_data->panel_roi.w,
+             dest_scalar_data->panel_roi.h);
+#endif
     DLOGV_IF(kTagDriverConfig, "*****************************************************************");
   }
   mdp_commit.dest_scaler_cnt = UINT32(hw_layer_info.dest_scale_info_map.size());
@@ -365,9 +374,16 @@
   DLOGI("right_roi: x = %d, y = %d, w = %d, h = %d", r_roi.x, r_roi.y, r_roi.w, r_roi.h);
   for (uint32_t i = 0; i < mdp_commit.dest_scaler_cnt; i++) {
     mdp_destination_scaler_data *dest_scalar_data = &mdp_dest_scalar_data_[i];
+    mdp_scale_data_v2 *mdp_scale = reinterpret_cast<mdp_scale_data_v2 *>(dest_scalar_data->scale);
 
     DLOGI("Dest scalar index %d Mixer WxH %dx%d", dest_scalar_data->dest_scaler_ndx,
           dest_scalar_data->lm_width, dest_scalar_data->lm_height);
+#ifdef MDP_DESTSCALER_ROI_ENABLE
+    DLOGI("Panel ROI [%d, %d, %d, %d]", dest_scalar_data->panel_roi.x,
+           dest_scalar_data->panel_roi.y, dest_scalar_data->panel_roi.w,
+           dest_scalar_data->panel_roi.h);
+#endif
+    DLOGI("Dest scalar Dst WxH %dx%d", mdp_scale->dst_width, mdp_scale->dst_height);
   }
   for (uint32_t i = 0; i < mdp_commit.input_layer_cnt; i++) {
     const mdp_input_layer &layer = mdp_layers[i];
@@ -639,7 +655,6 @@
   case kFormatYCrCb420PlanarStride16:
   case kFormatYCbCr420SemiPlanar:
   case kFormatYCrCb420SemiPlanar:
-  case kFormatYCbCr420P010:
   case kFormatYCbCr420TP10Ubwc:
     *target = width;
     break;
@@ -649,6 +664,7 @@
   case kFormatYCrCb422H1V2SemiPlanar:
   case kFormatYCbCr422H2V1SemiPlanar:
   case kFormatYCbCr422H1V2SemiPlanar:
+  case kFormatYCbCr420P010:
   case kFormatRGBA5551:
   case kFormatRGBA4444:
     *target = width * 2;
diff --git a/sdm/libs/core/fb/hw_primary.cpp b/sdm/libs/core/fb/hw_primary.cpp
index 3fdc8b2..1e6f37d 100644
--- a/sdm/libs/core/fb/hw_primary.cpp
+++ b/sdm/libs/core/fb/hw_primary.cpp
@@ -302,10 +302,6 @@
     return kErrorNotSupported;
   }
 
-  if (refresh_rate == display_attributes_.fps) {
-    return kErrorNone;
-  }
-
   snprintf(node_path, sizeof(node_path), "%s%d/dynamic_fps", fb_path_, fb_node_index_);
 
   int fd = Sys::open_(node_path, O_WRONLY);
diff --git a/sdm/libs/core/strategy.cpp b/sdm/libs/core/strategy.cpp
index aa89e64..a34c40c 100644
--- a/sdm/libs/core/strategy.cpp
+++ b/sdm/libs/core/strategy.cpp
@@ -57,7 +57,7 @@
     }
 
     error = extension_intf_->CreatePartialUpdate(display_type_, hw_resource_info_, hw_panel_info_,
-                                                 mixer_attributes_, display_attributes_,
+                                                 mixer_attributes_, display_attributes_, fb_config_,
                                                  &partial_update_intf_);
   }
 
@@ -215,7 +215,7 @@
   }
 
   extension_intf_->CreatePartialUpdate(display_type_, hw_resource_info_, hw_panel_info,
-                                       mixer_attributes, display_attributes,
+                                       mixer_attributes, display_attributes, fb_config,
                                        &partial_update_intf_);
 
   error = strategy_intf_->Reconfigure(hw_panel_info, hw_resource_info_, mixer_attributes,
diff --git a/sdm/libs/hwc/hwc_display.cpp b/sdm/libs/hwc/hwc_display.cpp
index aff6bbf..c1e4134 100644
--- a/sdm/libs/hwc/hwc_display.cpp
+++ b/sdm/libs/hwc/hwc_display.cpp
@@ -567,7 +567,7 @@
         bool secure = (pvt_handle->flags & private_handle_t::PRIV_FLAGS_SECURE_BUFFER) ||
                 (pvt_handle->flags & private_handle_t::PRIV_FLAGS_PROTECTED_BUFFER) ||
                 (pvt_handle->flags & private_handle_t::PRIV_FLAGS_SECURE_DISPLAY);
-        if (NonIntegralSourceCrop && !secure) {
+        if (NonIntegralSourceCrop && (!secure && pvt_handle->bufferType != BUFFER_TYPE_VIDEO)) {
             layer->flags.skip = true;
         }
     }
diff --git a/sdm/libs/hwc/hwc_display_primary.cpp b/sdm/libs/hwc/hwc_display_primary.cpp
index 7f52ae7..d12897e 100644
--- a/sdm/libs/hwc/hwc_display_primary.cpp
+++ b/sdm/libs/hwc/hwc_display_primary.cpp
@@ -192,7 +192,9 @@
   }
 
   uint32_t refresh_rate = GetOptimalRefreshRate(one_updating_layer);
-  if (current_refresh_rate_ != refresh_rate) {
+  // TODO(user): Need to read current refresh rate to avoid
+  // redundant calls to set refresh rate during idle fall back.
+  if ((current_refresh_rate_ != refresh_rate) || (handle_idle_timeout_)) {
     error = display_intf_->SetRefreshRate(refresh_rate);
   }
 
diff --git a/sdm/libs/hwc2/Android.mk b/sdm/libs/hwc2/Android.mk
index 3351ced..d4ff53c 100644
--- a/sdm/libs/hwc2/Android.mk
+++ b/sdm/libs/hwc2/Android.mk
@@ -16,23 +16,31 @@
 LOCAL_CLANG                   := true
 
 LOCAL_SHARED_LIBRARIES        := libsdmcore libqservice libbinder libhardware libhardware_legacy \
-                                 libutils libcutils libsync libmemalloc libqdutils libdl \
+                                 libutils libcutils libsync libqdutils libdl \
                                  libpowermanager libsdmutils libc++ liblog
 
+ifneq ($(TARGET_USES_GRALLOC1), true)
+    LOCAL_SHARED_LIBRARIES += libmemalloc
+endif
+
 LOCAL_SRC_FILES               := hwc_session.cpp \
                                  hwc_display.cpp \
                                  hwc_display_primary.cpp \
                                  hwc_display_external.cpp \
                                  hwc_display_virtual.cpp \
                                  ../hwc/hwc_debugger.cpp \
-                                 ../hwc/hwc_buffer_allocator.cpp \
                                  ../hwc/hwc_buffer_sync_handler.cpp \
                                  hwc_color_manager.cpp \
                                  hwc_layers.cpp \
                                  hwc_callbacks.cpp \
-                                 ../hwc/blit_engine_c2d.cpp \
                                  ../hwc/cpuhint.cpp \
                                  ../hwc/hwc_socket_handler.cpp
 
+ifneq ($(TARGET_USES_GRALLOC1), true)
+    LOCAL_SRC_FILES += ../hwc/hwc_buffer_allocator.cpp
+else
+    LOCAL_SRC_FILES += hwc_buffer_allocator.cpp
+endif
+
 include $(BUILD_SHARED_LIBRARY)
 endif
diff --git a/sdm/libs/hwc2/hwc_buffer_allocator.cpp b/sdm/libs/hwc2/hwc_buffer_allocator.cpp
new file mode 100644
index 0000000..5e3cd86
--- /dev/null
+++ b/sdm/libs/hwc2/hwc_buffer_allocator.cpp
@@ -0,0 +1,310 @@
+/*
+* Copyright (c) 2015-2017, The Linux Foundation. All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are
+* met:
+*  * Redistributions of source code must retain the above copyright
+*    notice, this list of conditions and the following disclaimer.
+*  * Redistributions in binary form must reproduce the above
+*    copyright notice, this list of conditions and the following
+*    disclaimer in the documentation and/or other materials provided
+*    with the distribution.
+*  * Neither the name of The Linux Foundation nor the names of its
+*    contributors may be used to endorse or promote products derived
+*    from this software without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include <gralloc_priv.h>
+
+#include <core/buffer_allocator.h>
+#include <utils/constants.h>
+#include <utils/debug.h>
+
+#include "hwc_buffer_allocator.h"
+#include "hwc_debugger.h"
+
+#define __CLASS__ "HWCBufferAllocator"
+namespace sdm {
+
+HWCBufferAllocator::HWCBufferAllocator() {
+  int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module_);
+  if (err != 0) {
+    DLOGE("FATAL: can not open GRALLOC module");
+  } else {
+    gralloc1_open(module_, &gralloc_device_);
+  }
+  ReleaseBuffer_ = reinterpret_cast<GRALLOC1_PFN_RELEASE>(
+      gralloc_device_->getFunction(gralloc_device_, GRALLOC1_FUNCTION_RELEASE));
+  Perform_ = reinterpret_cast<GRALLOC1_PFN_PERFORM>(
+      gralloc_device_->getFunction(gralloc_device_, GRALLOC1_FUNCTION_PERFORM));
+}
+
+HWCBufferAllocator::~HWCBufferAllocator() {
+  if (gralloc_device_ != nullptr) {
+    gralloc1_close(gralloc_device_);
+  }
+}
+
+DisplayError HWCBufferAllocator::AllocateBuffer(BufferInfo *buffer_info) {
+  const BufferConfig &buffer_config = buffer_info->buffer_config;
+  AllocatedBufferInfo *alloc_buffer_info = &buffer_info->alloc_buffer_info;
+  uint32_t width = buffer_config.width;
+  uint32_t height = buffer_config.height;
+  int format;
+  int alloc_flags = 0;
+  int error = SetBufferInfo(buffer_config.format, &format, &alloc_flags);
+  if (error != 0) {
+    return kErrorParameters;
+  }
+
+  if (buffer_config.secure) {
+    alloc_flags |= GRALLOC1_PRODUCER_USAGE_PROTECTED;
+  }
+
+  if (!buffer_config.cache) {
+    // Allocate uncached buffers
+    alloc_flags |= GRALLOC_USAGE_PRIVATE_UNCACHED;
+  }
+  uint64_t producer_usage = UINT64(alloc_flags);
+  uint64_t consumer_usage = UINT64(alloc_flags);
+  // CreateBuffer
+  private_handle_t *hnd = nullptr;
+  Perform_(gralloc_device_, GRALLOC1_MODULE_PERFORM_ALLOCATE_BUFFER, width, height, format,
+           producer_usage, consumer_usage, &hnd);
+
+  if (hnd) {
+    alloc_buffer_info->fd = hnd->fd;
+    alloc_buffer_info->stride = UINT32(hnd->width);
+    alloc_buffer_info->size = hnd->size;
+  } else {
+    DLOGE("Failed to allocate memory");
+    return kErrorMemory;
+  }
+
+  buffer_info->private_data = reinterpret_cast<void *>(hnd);
+  return kErrorNone;
+}
+
+DisplayError HWCBufferAllocator::FreeBuffer(BufferInfo *buffer_info) {
+  DisplayError err = kErrorNone;
+  buffer_handle_t hnd = static_cast<private_handle_t *>(buffer_info->private_data);
+  ReleaseBuffer_(gralloc_device_, hnd);
+  AllocatedBufferInfo *alloc_buffer_info = &buffer_info->alloc_buffer_info;
+  alloc_buffer_info->fd = -1;
+  alloc_buffer_info->stride = 0;
+  alloc_buffer_info->size = 0;
+  return err;
+}
+
+void HWCBufferAllocator::GetCustomWidthAndHeight(const private_handle_t *handle, int *width,
+                                                 int *height) {
+  Perform_(gralloc_device_, GRALLOC_MODULE_PERFORM_GET_CUSTOM_STRIDE_AND_HEIGHT_FROM_HANDLE, handle,
+           width, height);
+}
+
+void HWCBufferAllocator::GetAlignedWidthAndHeight(int width, int height, int format,
+                                                  uint32_t alloc_type, int *aligned_width,
+                                                  int *aligned_height) {
+  int tile_enabled;
+  gralloc1_producer_usage_t producer_usage = GRALLOC1_PRODUCER_USAGE_NONE;
+  gralloc1_consumer_usage_t consumer_usage = GRALLOC1_CONSUMER_USAGE_NONE;
+  if (alloc_type & GRALLOC_USAGE_HW_FB) {
+    consumer_usage = GRALLOC1_CONSUMER_USAGE_CLIENT_TARGET;
+  }
+
+  Perform_(gralloc_device_, GRALLOC_MODULE_PERFORM_GET_ATTRIBUTES, width, height, format,
+           producer_usage, consumer_usage, aligned_width, aligned_height, &tile_enabled);
+}
+
+uint32_t HWCBufferAllocator::GetBufferSize(BufferInfo *buffer_info) {
+  const BufferConfig &buffer_config = buffer_info->buffer_config;
+  int alloc_flags = INT(GRALLOC_USAGE_PRIVATE_IOMMU_HEAP);
+
+  int width = INT(buffer_config.width);
+  int height = INT(buffer_config.height);
+  int format;
+
+  if (buffer_config.secure) {
+    alloc_flags |= INT(GRALLOC_USAGE_PROTECTED);
+  }
+
+  if (!buffer_config.cache) {
+    // Allocate uncached buffers
+    alloc_flags |= GRALLOC_USAGE_PRIVATE_UNCACHED;
+  }
+
+  if (SetBufferInfo(buffer_config.format, &format, &alloc_flags) < 0) {
+    return 0;
+  }
+
+  uint32_t aligned_width = 0, aligned_height = 0, buffer_size = 0;
+  uint64_t producer_usage = GRALLOC1_PRODUCER_USAGE_NONE;
+  uint64_t consumer_usage = GRALLOC1_CONSUMER_USAGE_NONE;
+  // TODO(user): Currently both flags are treated similarly in gralloc
+  producer_usage = UINT64(alloc_flags);
+  consumer_usage = producer_usage;
+  Perform_(gralloc_device_, GRALLOC1_MODULE_PERFORM_GET_BUFFER_SIZE_AND_DIMENSIONS, width, height,
+           format, producer_usage, consumer_usage, &aligned_width, &aligned_height, &buffer_size);
+  return buffer_size;
+}
+
+int HWCBufferAllocator::SetBufferInfo(LayerBufferFormat format, int *target, int *flags) {
+  switch (format) {
+    case kFormatRGBA8888:
+      *target = HAL_PIXEL_FORMAT_RGBA_8888;
+      break;
+    case kFormatRGBX8888:
+      *target = HAL_PIXEL_FORMAT_RGBX_8888;
+      break;
+    case kFormatRGB888:
+      *target = HAL_PIXEL_FORMAT_RGB_888;
+      break;
+    case kFormatRGB565:
+      *target = HAL_PIXEL_FORMAT_RGB_565;
+      break;
+    case kFormatBGR565:
+      *target = HAL_PIXEL_FORMAT_BGR_565;
+      break;
+    case kFormatBGRA8888:
+      *target = HAL_PIXEL_FORMAT_BGRA_8888;
+      break;
+    case kFormatYCrCb420PlanarStride16:
+      *target = HAL_PIXEL_FORMAT_YV12;
+      break;
+    case kFormatYCrCb420SemiPlanar:
+      *target = HAL_PIXEL_FORMAT_YCrCb_420_SP;
+      break;
+    case kFormatYCbCr420SemiPlanar:
+      *target = HAL_PIXEL_FORMAT_YCbCr_420_SP;
+      break;
+    case kFormatYCbCr422H2V1Packed:
+      *target = HAL_PIXEL_FORMAT_YCbCr_422_I;
+      break;
+    case kFormatYCbCr422H2V1SemiPlanar:
+      *target = HAL_PIXEL_FORMAT_YCbCr_422_SP;
+      break;
+    case kFormatYCbCr420SemiPlanarVenus:
+      *target = HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS;
+      break;
+    case kFormatYCrCb420SemiPlanarVenus:
+      *target = HAL_PIXEL_FORMAT_YCrCb_420_SP_VENUS;
+      break;
+    case kFormatYCbCr420SPVenusUbwc:
+      *target = HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC;
+      break;
+    case kFormatRGBA5551:
+      *target = HAL_PIXEL_FORMAT_RGBA_5551;
+      break;
+    case kFormatRGBA4444:
+      *target = HAL_PIXEL_FORMAT_RGBA_4444;
+      break;
+    case kFormatRGBA1010102:
+      *target = HAL_PIXEL_FORMAT_RGBA_1010102;
+      break;
+    case kFormatARGB2101010:
+      *target = HAL_PIXEL_FORMAT_ARGB_2101010;
+      break;
+    case kFormatRGBX1010102:
+      *target = HAL_PIXEL_FORMAT_RGBX_1010102;
+      break;
+    case kFormatXRGB2101010:
+      *target = HAL_PIXEL_FORMAT_XRGB_2101010;
+      break;
+    case kFormatBGRA1010102:
+      *target = HAL_PIXEL_FORMAT_BGRA_1010102;
+      break;
+    case kFormatABGR2101010:
+      *target = HAL_PIXEL_FORMAT_ABGR_2101010;
+      break;
+    case kFormatBGRX1010102:
+      *target = HAL_PIXEL_FORMAT_BGRX_1010102;
+      break;
+    case kFormatXBGR2101010:
+      *target = HAL_PIXEL_FORMAT_XBGR_2101010;
+      break;
+    case kFormatYCbCr420P010:
+      *target = HAL_PIXEL_FORMAT_YCbCr_420_P010;
+      break;
+    case kFormatYCbCr420TP10Ubwc:
+      *target = HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC;
+      break;
+    case kFormatRGBA8888Ubwc:
+      *target = HAL_PIXEL_FORMAT_RGBA_8888;
+      *flags |= GRALLOC_USAGE_PRIVATE_ALLOC_UBWC;
+      break;
+    case kFormatRGBX8888Ubwc:
+      *target = HAL_PIXEL_FORMAT_RGBX_8888;
+      *flags |= GRALLOC_USAGE_PRIVATE_ALLOC_UBWC;
+      break;
+    case kFormatBGR565Ubwc:
+      *target = HAL_PIXEL_FORMAT_BGR_565;
+      *flags |= GRALLOC_USAGE_PRIVATE_ALLOC_UBWC;
+      break;
+    case kFormatRGBA1010102Ubwc:
+      *target = HAL_PIXEL_FORMAT_RGBA_1010102;
+      *flags |= GRALLOC_USAGE_PRIVATE_ALLOC_UBWC;
+      break;
+    case kFormatRGBX1010102Ubwc:
+      *target = HAL_PIXEL_FORMAT_RGBX_1010102;
+      *flags |= GRALLOC_USAGE_PRIVATE_ALLOC_UBWC;
+      break;
+    default:
+      DLOGE("Unsupported format = 0x%x", format);
+      return -EINVAL;
+  }
+  return 0;
+}
+
+DisplayError HWCBufferAllocator::GetAllocatedBufferInfo(
+    const BufferConfig &buffer_config, AllocatedBufferInfo *allocated_buffer_info) {
+  // TODO(user): This API should pass the buffer_info of the already allocated buffer
+  // The private_data can then be typecast to the private_handle and used directly.
+  int alloc_flags = INT(GRALLOC_USAGE_PRIVATE_IOMMU_HEAP);
+
+  int width = INT(buffer_config.width);
+  int height = INT(buffer_config.height);
+  int format;
+
+  if (buffer_config.secure) {
+    alloc_flags |= INT(GRALLOC_USAGE_PROTECTED);
+  }
+
+  if (!buffer_config.cache) {
+    // Allocate uncached buffers
+    alloc_flags |= GRALLOC_USAGE_PRIVATE_UNCACHED;
+  }
+
+  if (SetBufferInfo(buffer_config.format, &format, &alloc_flags) < 0) {
+    return kErrorParameters;
+  }
+
+  uint32_t aligned_width = 0, aligned_height = 0, buffer_size = 0;
+  uint64_t producer_usage = GRALLOC1_PRODUCER_USAGE_NONE;
+  uint64_t consumer_usage = GRALLOC1_CONSUMER_USAGE_NONE;
+  // TODO(user): Currently both flags are treated similarly in gralloc
+  producer_usage = UINT64(alloc_flags);
+  consumer_usage = producer_usage;
+  Perform_(gralloc_device_, GRALLOC1_MODULE_PERFORM_GET_BUFFER_SIZE_AND_DIMENSIONS, width, height,
+           format, producer_usage, consumer_usage, &aligned_width, &aligned_height, &buffer_size);
+  allocated_buffer_info->stride = UINT32(aligned_width);
+  allocated_buffer_info->aligned_width = UINT32(aligned_width);
+  allocated_buffer_info->aligned_height = UINT32(aligned_height);
+  allocated_buffer_info->size = UINT32(buffer_size);
+
+  return kErrorNone;
+}
+
+}  // namespace sdm
diff --git a/sdm/libs/hwc2/hwc_buffer_allocator.h b/sdm/libs/hwc2/hwc_buffer_allocator.h
new file mode 100644
index 0000000..c28a94e
--- /dev/null
+++ b/sdm/libs/hwc2/hwc_buffer_allocator.h
@@ -0,0 +1,74 @@
+/*
+* Copyright (c) 2015-2017, The Linux Foundation. All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are
+* met:
+*  * Redistributions of source code must retain the above copyright
+*    notice, this list of conditions and the following disclaimer.
+*  * Redistributions in binary form must reproduce the above
+*    copyright notice, this list of conditions and the following
+*    disclaimer in the documentation and/or other materials provided
+*    with the distribution.
+*  * Neither the name of The Linux Foundation nor the names of its
+*    contributors may be used to endorse or promote products derived
+*    from this software without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+#ifdef USE_GRALLOC1
+#ifndef __HWC_BUFFER_ALLOCATOR_H__
+#define __HWC_BUFFER_ALLOCATOR_H__
+
+#include <fcntl.h>
+#include <sys/mman.h>
+
+#include <hardware/gralloc1.h>
+#include "gralloc_priv.h"
+
+namespace sdm {
+
+template <class Type>
+inline Type ALIGN(Type x, Type align) {
+  return (x + align - 1) & ~(align - 1);
+}
+
+class HWCBufferAllocator : public BufferAllocator {
+ public:
+  HWCBufferAllocator();
+  ~HWCBufferAllocator();
+
+  DisplayError AllocateBuffer(BufferInfo *buffer_info);
+  DisplayError FreeBuffer(BufferInfo *buffer_info);
+  uint32_t GetBufferSize(BufferInfo *buffer_info);
+
+  void GetCustomWidthAndHeight(const private_handle_t *handle, int *width, int *height);
+  void GetAlignedWidthAndHeight(int width, int height, int format, uint32_t alloc_type,
+                                int *aligned_width, int *aligned_height);
+  DisplayError GetAllocatedBufferInfo(const BufferConfig &buffer_config,
+                                      AllocatedBufferInfo *allocated_buffer_info);
+  int SetBufferInfo(LayerBufferFormat format, int *target, int *flags);
+
+ private:
+  gralloc1_device_t *gralloc_device_ = nullptr;
+  const hw_module_t *module_;
+  GRALLOC1_PFN_RELEASE ReleaseBuffer_ = nullptr;
+  GRALLOC1_PFN_PERFORM Perform_ = nullptr;
+};
+
+}  // namespace sdm
+#endif  // __HWC_BUFFER_ALLOCATOR_H__
+#else
+#include "../hwc/hwc_buffer_allocator.h"
+#endif  // __HWC_BUFFER_ALLOCATOR_H__
+
diff --git a/sdm/libs/hwc2/hwc_display.cpp b/sdm/libs/hwc2/hwc_display.cpp
index 382e234..e3b0523 100644
--- a/sdm/libs/hwc2/hwc_display.cpp
+++ b/sdm/libs/hwc2/hwc_display.cpp
@@ -19,8 +19,6 @@
 
 #include <cutils/properties.h>
 #include <errno.h>
-#include <gr.h>
-#include <gralloc_priv.h>
 #include <math.h>
 #include <sync/sync.h>
 #include <utils/constants.h>
@@ -39,6 +37,9 @@
 #include "hwc_display.h"
 #include "hwc_debugger.h"
 #include "blit_engine_c2d.h"
+#ifndef USE_GRALLOC1
+#include <gr.h>
+#endif
 
 #ifdef QTI_BSP
 #include <hardware/display_defs.h>
@@ -236,21 +237,14 @@
     swap_interval_zero_ = true;
   }
 
+  buffer_allocator_ = new HWCBufferAllocator();
 
-  client_target_ = new HWCLayer(id_);
+  client_target_ = new HWCLayer(id_, buffer_allocator_);
+
   int blit_enabled = 0;
   HWCDebugHandler::Get()->GetProperty("persist.hwc.blit.comp", &blit_enabled);
   if (needs_blit_ && blit_enabled) {
-    blit_engine_ = new BlitEngineC2d();
-    if (!blit_engine_) {
-      DLOGI("Create Blit Engine C2D failed");
-    } else {
-      if (blit_engine_->Init() < 0) {
-        DLOGI("Blit Engine Init failed, Blit Composition will not be used!!");
-        delete blit_engine_;
-        blit_engine_ = NULL;
-      }
-    }
+    // TODO(user): Add blit engine when needed
   }
 
   display_intf_->GetRefreshRateRange(&min_refresh_rate_, &max_refresh_rate_);
@@ -268,10 +262,9 @@
 
   delete client_target_;
 
-  if (blit_engine_) {
-    blit_engine_->DeInit();
-    delete blit_engine_;
-    blit_engine_ = NULL;
+  if (buffer_allocator_) {
+    delete buffer_allocator_;
+    buffer_allocator_ = NULL;
   }
 
   if (color_mode_) {
@@ -284,7 +277,7 @@
 
 // LayerStack operations
 HWC2::Error HWCDisplay::CreateLayer(hwc2_layer_t *out_layer_id) {
-  HWCLayer *layer = *layer_set_.emplace(new HWCLayer(id_));
+  HWCLayer *layer = *layer_set_.emplace(new HWCLayer(id_, buffer_allocator_));
   layer_map_.emplace(std::make_pair(layer->GetId(), layer));
   *out_layer_id = layer->GetId();
   geometry_changes_ |= GeometryChanges::kAdded;
@@ -351,7 +344,11 @@
     const private_handle_t *handle =
         reinterpret_cast<const private_handle_t *>(layer->input_buffer.buffer_id);
     if (handle) {
+#ifdef USE_GRALLOC1
+      if (handle->buffer_type == BUFFER_TYPE_VIDEO) {
+#else
       if (handle->bufferType == BUFFER_TYPE_VIDEO) {
+#endif
         layer_stack_.flags.video_present = true;
       }
       // TZ Protected Buffer - L1
@@ -688,10 +685,6 @@
   dump_frame_index_ = 0;
   dump_input_layers_ = ((bit_mask_layer_type & (1 << INPUT_LAYER_DUMP)) != 0);
 
-  if (blit_engine_) {
-    blit_engine_->SetFrameDumpConfig(count);
-  }
-
   DLOGI("num_frame_dump %d, input_layer_dump_enable %d", dump_frame_count_, dump_input_layers_);
 }
 
@@ -1264,7 +1257,7 @@
 
   int aligned_width;
   int aligned_height;
-  int usage = GRALLOC_USAGE_HW_FB;
+  uint32_t usage = GRALLOC_USAGE_HW_FB;
   int format = HAL_PIXEL_FORMAT_RGBA_8888;
   int ubwc_enabled = 0;
   int flags = 0;
@@ -1273,8 +1266,14 @@
     usage |= GRALLOC_USAGE_PRIVATE_ALLOC_UBWC;
     flags |= private_handle_t::PRIV_FLAGS_UBWC_ALIGNED;
   }
-  AdrenoMemInfo::getInstance().getAlignedWidthAndHeight(INT(x_pixels), INT(y_pixels), format, usage,
-                                                        aligned_width, aligned_height);
+
+#ifdef USE_GRALLOC1
+  buffer_allocator_->GetAlignedWidthAndHeight(INT(x_pixels), INT(y_pixels), format, usage,
+                                              &aligned_width, &aligned_height);
+#else
+  AdrenoMemInfo::getInstance().getAlignedWidthAndHeight(INT(x_pixels), INT(y_pixels), format,
+                                                        INT(usage), aligned_width, aligned_height);
+#endif
 
   // TODO(user): How does the dirty region get set on the client target? File bug on Google
   client_target_layer->composition = kCompositionGPUTarget;
diff --git a/sdm/libs/hwc2/hwc_display.h b/sdm/libs/hwc2/hwc_display.h
index bc3c929..d8f85bd 100644
--- a/sdm/libs/hwc2/hwc_display.h
+++ b/sdm/libs/hwc2/hwc_display.h
@@ -32,6 +32,7 @@
 #include <utility>
 #include <vector>
 
+#include "hwc_buffer_allocator.h"
 #include "hwc_callbacks.h"
 #include "hwc_layers.h"
 
@@ -229,6 +230,7 @@
 
   CoreInterface *core_intf_ = nullptr;
   HWCCallbacks *callbacks_  = nullptr;
+  HWCBufferAllocator *buffer_allocator_ = NULL;
   DisplayType type_;
   hwc2_display_t id_;
   bool needs_blit_ = false;
@@ -269,7 +271,6 @@
 
  private:
   void DumpInputBuffers(void);
-  BlitEngine *blit_engine_ = NULL;
   qService::QService *qservice_ = NULL;
   DisplayClass display_class_;
   uint32_t geometry_changes_ = GeometryChanges::kNone;
diff --git a/sdm/libs/hwc2/hwc_display_virtual.cpp b/sdm/libs/hwc2/hwc_display_virtual.cpp
index 1197c7b..46fec4e 100644
--- a/sdm/libs/hwc2/hwc_display_virtual.cpp
+++ b/sdm/libs/hwc2/hwc_display_virtual.cpp
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2014 - 2016, The Linux Foundation. All rights reserved.
+* Copyright (c) 2014-2017, The Linux Foundation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
@@ -31,7 +31,9 @@
 #include <utils/debug.h>
 #include <sync/sync.h>
 #include <stdarg.h>
+#ifndef USE_GRALLOC1
 #include <gr.h>
+#endif
 
 #include "hwc_display_virtual.h"
 #include "hwc_debugger.h"
@@ -189,18 +191,17 @@
     }
 
     int aligned_width, aligned_height;
-    int unaligned_width, unaligned_height;
-
+#ifdef USE_GRALLOC1
+    buffer_allocator_->GetCustomWidthAndHeight(output_handle, &aligned_width, &aligned_height);
+#else
     AdrenoMemInfo::getInstance().getAlignedWidthAndHeight(output_handle, aligned_width,
                                                           aligned_height);
-    AdrenoMemInfo::getInstance().getUnalignedWidthAndHeight(output_handle, unaligned_width,
-                                                            unaligned_height);
+#endif
 
     output_buffer_->width = UINT32(aligned_width);
     output_buffer_->height = UINT32(aligned_height);
-    output_buffer_->unaligned_width = UINT32(unaligned_width);
-    output_buffer_->unaligned_height = UINT32(unaligned_height);
-    // TODO(mkavm): Handle DRC and metadata changes
+    output_buffer_->unaligned_width = UINT32(output_handle->unaligned_width);
+    output_buffer_->unaligned_height = UINT32(output_handle->unaligned_height);
     output_buffer_->flags.secure = 0;
     output_buffer_->flags.video = 0;
 
diff --git a/sdm/libs/hwc2/hwc_layers.cpp b/sdm/libs/hwc2/hwc_layers.cpp
index c8fd163..440f047 100644
--- a/sdm/libs/hwc2/hwc_layers.cpp
+++ b/sdm/libs/hwc2/hwc_layers.cpp
@@ -18,7 +18,9 @@
  */
 
 #include "hwc_layers.h"
+#ifndef USE_GRALLOC1
 #include <gr.h>
+#endif
 #include <utils/debug.h>
 #include <cmath>
 
@@ -64,7 +66,8 @@
 }
 
 // Layer operations
-HWCLayer::HWCLayer(hwc2_display_t display_id) : id_(next_id_++), display_id_(display_id) {
+HWCLayer::HWCLayer(hwc2_display_t display_id, HWCBufferAllocator *buf_allocator)
+  : id_(next_id_++), display_id_(display_id), buffer_allocator_(buf_allocator) {
   layer_ = new Layer();
   // Fences are deferred, so the first time this layer is presented, return -1
   // TODO(user): Verify that fences are properly obtained on suspend/resume
@@ -107,23 +110,28 @@
 
   LayerBuffer *layer_buffer = &layer_->input_buffer;
   int aligned_width, aligned_height;
-  int unaligned_width, unaligned_height;
-
+#ifdef USE_GRALLOC1
+  buffer_allocator_->GetCustomWidthAndHeight(handle, &aligned_width, &aligned_height);
+#else
   AdrenoMemInfo::getInstance().getAlignedWidthAndHeight(handle, aligned_width, aligned_height);
-  AdrenoMemInfo::getInstance().getUnalignedWidthAndHeight(handle, unaligned_width,
-                                                          unaligned_height);
+#endif
 
   layer_buffer->width = UINT32(aligned_width);
   layer_buffer->height = UINT32(aligned_height);
-  layer_buffer->unaligned_width = UINT32(unaligned_width);
-  layer_buffer->unaligned_height = UINT32(unaligned_height);
+  layer_buffer->unaligned_width = UINT32(handle->unaligned_width);
+  layer_buffer->unaligned_height = UINT32(handle->unaligned_height);
 
   layer_buffer->format = GetSDMFormat(handle->format, handle->flags);
   if (SetMetaData(handle, layer_) != kErrorNone) {
     return HWC2::Error::BadLayer;
   }
 
-  if (handle->bufferType == BUFFER_TYPE_VIDEO) {
+#ifdef USE_GRALLOC1
+  // TODO(user): Clean this up
+  if (handle->buffer_type == BUFFER_TYPE_VIDEO) {
+#else
+    if (handle->bufferType == BUFFER_TYPE_VIDEO) {
+#endif
     layer_buffer->flags.video = true;
   }
   // TZ Protected Buffer - L1
diff --git a/sdm/libs/hwc2/hwc_layers.h b/sdm/libs/hwc2/hwc_layers.h
index 6a80b1b..f9cb23e 100644
--- a/sdm/libs/hwc2/hwc_layers.h
+++ b/sdm/libs/hwc2/hwc_layers.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014-2016, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2014-2017, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright 2015 The Android Open Source Project
@@ -31,9 +31,11 @@
 #include <hardware/hwcomposer2.h>
 #undef HWC2_INCLUDE_STRINGIFICATION
 #undef HWC2_USE_CPP11
-#include <set>
 #include <map>
 #include <queue>
+#include <set>
+#include "core/buffer_allocator.h"
+#include "hwc_buffer_allocator.h"
 
 namespace sdm {
 
@@ -54,7 +56,7 @@
 
 class HWCLayer {
  public:
-  explicit HWCLayer(hwc2_display_t display_id);
+  explicit HWCLayer(hwc2_display_t display_id, HWCBufferAllocator *buf_allocator);
   ~HWCLayer();
   uint32_t GetZ() const { return z_; }
   hwc2_layer_t GetId() const { return id_; }
@@ -89,6 +91,7 @@
   static std::atomic<hwc2_layer_t> next_id_;
   std::queue<int32_t> release_fences_;
   int ion_fd_ = -1;
+  HWCBufferAllocator *buffer_allocator_ = NULL;
 
   // Composition requested by client(SF)
   HWC2::Composition client_requested_ = HWC2::Composition::Device;
diff --git a/sdm/libs/hwc2/hwc_session.cpp b/sdm/libs/hwc2/hwc_session.cpp
index ee4a6e7..cc780d8 100644
--- a/sdm/libs/hwc2/hwc_session.cpp
+++ b/sdm/libs/hwc2/hwc_session.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014-2016, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2014-2017, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright 2015 The Android Open Source Project
@@ -28,8 +28,6 @@
 #include <sys/prctl.h>
 #include <binder/Parcel.h>
 #include <QService.h>
-#include <gr.h>
-#include <gralloc_priv.h>
 #include <display_config.h>
 #include <utils/debug.h>
 #include <sync/sync.h>