Merge "composer: Add validation for display Id for DSI clock binder APIs"
diff --git a/composer/Android.mk b/composer/Android.mk
index 3c183cc..0202fed 100644
--- a/composer/Android.mk
+++ b/composer/Android.mk
@@ -65,6 +65,10 @@
                                  gl_layer_stitch_impl.cpp
 
 LOCAL_INIT_RC                 := vendor.qti.hardware.display.composer-service.rc
+ifneq ($(TARGET_HAS_LOW_RAM),true)
 LOCAL_VINTF_FRAGMENTS         := vendor.qti.hardware.display.composer-service.xml
+else
+LOCAL_VINTF_FRAGMENTS         := vendor.qti.hardware.display.composer-service-low-ram.xml
+endif
 
 include $(BUILD_EXECUTABLE)
diff --git a/composer/QtiComposerClient.cpp b/composer/QtiComposerClient.cpp
index eb3b36c..a7153fc 100644
--- a/composer/QtiComposerClient.cpp
+++ b/composer/QtiComposerClient.cpp
@@ -162,19 +162,22 @@
 void QtiComposerClient::onVsync_2_4(hwc2_callback_data_t callbackData, hwc2_display_t display,
                                     int64_t timestamp, VsyncPeriodNanos vsyncPeriodNanos) {
   auto client = reinterpret_cast<QtiComposerClient*>(callbackData);
-  VsyncPeriodNanos vsync_period;
-  client->hwc_session_->GetDisplayVsyncPeriod(display, &vsync_period);
-  auto ret = client->callback24_->onVsync_2_4(display, timestamp, vsync_period);
+  auto ret = client->callback24_->onVsync_2_4(display, timestamp, vsyncPeriodNanos);
   ALOGW_IF(!ret.isOk(), "failed to send onVsync_2_4: %s. SF likely unavailable.",
            ret.description().c_str());
 }
 
 void QtiComposerClient::onVsyncPeriodTimingChanged(hwc2_callback_data_t callbackData,
-      hwc2_display_t display, const VsyncPeriodChangeTimeline& updatedTimeline) {
+      hwc2_display_t display, hwc_vsync_period_change_timeline_t *updatedTimeline) {
+   VsyncPeriodChangeTimeline timeline =
+                                   {updatedTimeline->newVsyncAppliedTimeNanos,
+                                    static_cast<bool>(updatedTimeline->refreshRequired),
+                                    updatedTimeline->refreshTimeNanos};
+
   auto client = reinterpret_cast<QtiComposerClient*>(callbackData);
-  auto ret = client->callback24_->onVsyncPeriodTimingChanged(display, updatedTimeline);
+  auto ret = client->callback24_->onVsyncPeriodTimingChanged(display, timeline);
   ALOGW_IF(!ret.isOk(), "failed to send onVsyncPeriodTimingChanged: %s. SF likely unavailable.",
-           ret.description().c_str());
+          ret.description().c_str());
 }
 
 void QtiComposerClient::onSeamlessPossible(hwc2_callback_data_t callbackData,
@@ -961,7 +964,28 @@
                                                        getDisplayCapabilities_cb _hidl_cb) {
   // We only care about passing VTS for older composer versions
   // Not returning any capabilities that are optional
-  return Void();
+
+  hidl_vec<DisplayCapability_V2_3> capabilities;
+
+  uint32_t count = 0;
+  auto error = hwc_session_->GetDisplayCapabilities2_3(display, &count, nullptr);
+  if (error != HWC2_ERROR_NONE) {
+    _hidl_cb(static_cast<Error>(error), capabilities);
+    return Void();
+  }
+
+  capabilities.resize(count);
+  error = hwc_session_->GetDisplayCapabilities2_3(display, &count,
+                 reinterpret_cast<std::underlying_type<DisplayCapability_V2_3>::type*>(
+                 capabilities.data()));
+   if (error != HWC2_ERROR_NONE) {
+     capabilities = hidl_vec<DisplayCapability_V2_3>();
+     _hidl_cb(static_cast<Error>(error), capabilities);
+     return Void();
+   }
+
+   _hidl_cb(static_cast<Error>(error), capabilities);
+   return Void();
 }
 
 Return<void> QtiComposerClient::getPerFrameMetadataKeys_2_3(uint64_t display,
diff --git a/composer/QtiComposerClient.h b/composer/QtiComposerClient.h
index d11aaf4..77fb14e 100644
--- a/composer/QtiComposerClient.h
+++ b/composer/QtiComposerClient.h
@@ -49,6 +49,7 @@
 namespace composer_V2_3 = ::android::hardware::graphics::composer::V2_3;
 namespace composer_V2_4 = ::android::hardware::graphics::composer::V2_4;
 
+using DisplayCapability_V2_3 = composer_V2_3::IComposerClient::DisplayCapability;
 using PerFrameMetadataKey_V2 = composer_V2_2::IComposerClient::PerFrameMetadataKey;
 using PerFrameMetadataKey = composer_V2_3::IComposerClient::PerFrameMetadataKey;
 
@@ -224,7 +225,7 @@
                           int64_t timestamp, VsyncPeriodNanos vsyncPeriodNanos);
   static void onVsyncPeriodTimingChanged(hwc2_callback_data_t callbackData,
                                            hwc2_display_t display,
-                                           const VsyncPeriodChangeTimeline& updatedTimeline);
+                                           hwc_vsync_period_change_timeline_t* updatedTimeline);
   static void onSeamlessPossible(hwc2_callback_data_t callbackData, hwc2_display_t display);
 
   // Methods for ConcurrentWriteBack
diff --git a/composer/hwc_display.cpp b/composer/hwc_display.cpp
index 524a7c1..b0e811c 100644
--- a/composer/hwc_display.cpp
+++ b/composer/hwc_display.cpp
@@ -1058,7 +1058,7 @@
                                             int32_t *out_value) {
   if (variable_config_map_.find(config) == variable_config_map_.end()) {
     DLOGE("Get variable config failed");
-    return HWC2::Error::BadDisplay;
+    return HWC2::Error::BadConfig;
   }
 
   DisplayConfigVariableInfo variable_config = variable_config_map_.at(config);
diff --git a/composer/hwc_session.cpp b/composer/hwc_session.cpp
index 836ffc8..179a820 100644
--- a/composer/hwc_session.cpp
+++ b/composer/hwc_session.cpp
@@ -3235,27 +3235,59 @@
   }
 
   bool isBuiltin = (hwc_display_[display]->GetDisplayClass() == DISPLAY_CLASS_BUILTIN);
-  int32_t has_doze_support = 0;
-  GetDozeSupport(display, &has_doze_support);
   if (isBuiltin) {
-    capabilities->resize(4);
+    int32_t has_doze_support = 0;
+    GetDozeSupport(display, &has_doze_support);
+
     // TODO(user): Handle SKIP_CLIENT_COLOR_TRANSFORM based on DSPP availability
-    std::vector<HwcDisplayCapability> caps;
     if (has_doze_support) {
-      caps = {
-          HwcDisplayCapability::SKIP_CLIENT_COLOR_TRANSFORM, HwcDisplayCapability::DOZE,
-          HwcDisplayCapability::BRIGHTNESS, HwcDisplayCapability::PROTECTED_CONTENTS};
+      *capabilities = {HwcDisplayCapability::SKIP_CLIENT_COLOR_TRANSFORM,
+                       HwcDisplayCapability::DOZE,
+                       HwcDisplayCapability::BRIGHTNESS, HwcDisplayCapability::PROTECTED_CONTENTS};
+    } else {
+      *capabilities = {HwcDisplayCapability::SKIP_CLIENT_COLOR_TRANSFORM,
+                       HwcDisplayCapability::BRIGHTNESS, HwcDisplayCapability::PROTECTED_CONTENTS};
     }
-    else {
-      caps = {
-          HwcDisplayCapability::SKIP_CLIENT_COLOR_TRANSFORM,
-          HwcDisplayCapability::BRIGHTNESS, HwcDisplayCapability::PROTECTED_CONTENTS};
-    }
-    capabilities->setToExternal(caps.data(), caps.size());
   }
+
   return HWC2_ERROR_NONE;
 }
 
+int32_t HWCSession::GetDisplayCapabilities2_3(hwc2_display_t display, uint32_t *outNumCapabilities,
+                                              uint32_t *outCapabilities) {
+  if (!outNumCapabilities) {
+    return HWC2_ERROR_BAD_PARAMETER;
+  }
+
+  if (display >= HWCCallbacks::kNumDisplays) {
+    return HWC2_ERROR_BAD_DISPLAY;
+  }
+
+  if (!hwc_display_[display]) {
+    DLOGE("Expected valid hwc_display");
+    return HWC2_ERROR_BAD_PARAMETER;
+  }
+  bool isBuiltin = (hwc_display_[display]->GetDisplayClass() == DISPLAY_CLASS_BUILTIN);
+  if (!outCapabilities) {
+    *outNumCapabilities = 0;
+    if (isBuiltin) {
+      *outNumCapabilities = 2;
+    }
+    return HWC2_ERROR_NONE;
+  } else {
+    if (isBuiltin) {
+      uint32_t index = 0;
+      int32_t has_doze_support = 0;
+      GetDozeSupport(display, &has_doze_support);
+      if (has_doze_support) {
+        outCapabilities[index++] = HWC2_DISPLAY_CAPABILITY_DOZE;
+      }
+      outCapabilities[index++] = HWC2_DISPLAY_CAPABILITY_BRIGHTNESS;
+      *outNumCapabilities = index;
+    }
+  }
+  return HWC2_ERROR_NONE;
+}
 int32_t HWCSession::GetDisplayConnectionType(hwc2_display_t display,
                                              HwcDisplayConnectionType *type) {
   if (display >= HWCCallbacks::kNumDisplays) {
@@ -3268,7 +3300,7 @@
 
   if (!hwc_display_[display]) {
     DLOGE("Expected valid hwc_display");
-    return HWC2_ERROR_BAD_PARAMETER;
+    return HWC2_ERROR_BAD_DISPLAY;
   }
   *type = HwcDisplayConnectionType::EXTERNAL;
   if (hwc_display_[display]->GetDisplayClass() == DISPLAY_CLASS_BUILTIN) {
diff --git a/composer/hwc_session.h b/composer/hwc_session.h
index 680e54a..c0d718b 100644
--- a/composer/hwc_session.h
+++ b/composer/hwc_session.h
@@ -55,7 +55,9 @@
 using ::android::sp;
 using ::android::hardware::Void;
 namespace composer_V2_4 = ::android::hardware::graphics::composer::V2_4;
+namespace composer_V2_3 = ::android::hardware::graphics::composer::V2_3;
 using HwcDisplayCapability = composer_V2_4::IComposerClient::DisplayCapability;
+using HwcDisplayCapability_2_3 = composer_V2_3::IComposerClient::DisplayCapability;
 using HwcDisplayConnectionType = composer_V2_4::IComposerClient::DisplayConnectionType;
 
 namespace sdm {
@@ -197,6 +199,8 @@
                                        uint32_t *outDataSize, uint8_t *outData);
   int32_t GetDisplayCapabilities(hwc2_display_t display,
                                  hidl_vec<HwcDisplayCapability> *capabilities);
+  int32_t GetDisplayCapabilities2_3(hwc2_display_t display,
+                                    uint32_t *outNumCapabilities, uint32_t *outCapabilities);
   int32_t GetDisplayBrightnessSupport(hwc2_display_t display, bool *outSupport);
   int32_t SetDisplayBrightness(hwc2_display_t display, float brightness);
   void WaitForResources(bool wait_for_resources, hwc2_display_t active_builtin_id,
diff --git a/composer/hwc_session_services.cpp b/composer/hwc_session_services.cpp
index 4c31845..66ed32b 100644
--- a/composer/hwc_session_services.cpp
+++ b/composer/hwc_session_services.cpp
@@ -928,7 +928,7 @@
     return -1;
   }
 
-  if (disp_id != qdutils::DISPLAY_PRIMARY) {
+  if (disp_id != UINT32(DisplayConfig::DisplayType::kPrimary)) {
     DLOGE("Only supported for primary display at present.");
     return -1;
   }
@@ -941,6 +941,7 @@
   // Output buffer dump is not supported, if External or Virtual display is present.
   int external_dpy_index = hwc_session_->GetDisplayIndex(qdutils::DISPLAY_EXTERNAL);
   int virtual_dpy_index = hwc_session_->GetDisplayIndex(qdutils::DISPLAY_VIRTUAL);
+  int primary_dpy_index = hwc_session_->GetDisplayIndex(qdutils::DISPLAY_PRIMARY);
 
   if (((external_dpy_index != -1) && hwc_session_->hwc_display_[external_dpy_index]) ||
       ((virtual_dpy_index != -1) && hwc_session_->hwc_display_[virtual_dpy_index])) {
@@ -951,13 +952,14 @@
   // Mutex scope
   {
     SCOPE_LOCK(hwc_session_->locker_[HWC_DISPLAY_PRIMARY]);
-    if (!hwc_session_->hwc_display_[disp_id]) {
+    if (!hwc_session_->hwc_display_[primary_dpy_index]) {
       DLOGE("Display is not created yet.");
       return -1;
     }
   }
 
-  return hwc_session_->cwb_.PostBuffer(callback_, post_processed, buffer);
+  return hwc_session_->cwb_.PostBuffer(callback_, post_processed,
+                                       native_handle_clone(buffer));
 }
 
 int32_t HWCSession::CWB::PostBuffer(std::weak_ptr<DisplayConfig::ConfigCallback> callback,
@@ -1046,6 +1048,8 @@
       callback->NotifyCWBBufferDone(status, node->buffer);
     }
 
+    native_handle_close(node->buffer);
+    native_handle_delete(const_cast<native_handle_t *>(node->buffer));
     delete node;
 
     // Mutex scope
diff --git a/composer/vendor.qti.hardware.display.composer-service-low-ram.xml b/composer/vendor.qti.hardware.display.composer-service-low-ram.xml
new file mode 100644
index 0000000..ddf7610
--- /dev/null
+++ b/composer/vendor.qti.hardware.display.composer-service-low-ram.xml
@@ -0,0 +1,57 @@
+<!--
+Copyright (c) 2020, 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.
+-->
+<manifest version="1.0" type="device">
+    <hal format="hidl">
+        <name>vendor.qti.hardware.display.composer</name>
+        <transport>hwbinder</transport>
+        <version>2.1</version>
+        <interface>
+            <name>IQtiComposer</name>
+            <instance>default</instance>
+        </interface>
+    </hal>
+    <hal format="hidl">
+        <name>android.hardware.graphics.composer</name>
+        <transport>hwbinder</transport>
+        <version>2.3</version>
+        <interface>
+            <name>IComposer</name>
+            <instance>default</instance>
+        </interface>
+    </hal>
+    <hal format="hidl">
+        <name>vendor.display.config</name>
+        <transport>hwbinder</transport>
+        <version>1.15</version>
+        <interface>
+            <name>IDisplayConfig</name>
+            <instance>default</instance>
+        </interface>
+    </hal>
+</manifest>
diff --git a/config/display-product.mk b/config/display-product.mk
index 295ec87..636644f 100644
--- a/config/display-product.mk
+++ b/config/display-product.mk
@@ -42,6 +42,17 @@
 #QDCM calibration xml file for Sharp 2k panel
 PRODUCT_COPY_FILES += hardware/qcom/display/config/qdcm_calib_data_default.xml:$(TARGET_COPY_OUT_VENDOR)/etc/qdcm_calib_data_Sharp_2k_cmd_mode_qsync_dsi_panel.xml
 PRODUCT_COPY_FILES += hardware/qcom/display/config/qdcm_calib_data_default.xml:$(TARGET_COPY_OUT_VENDOR)/etc/qdcm_calib_data_Sharp_2k_video_mode_qsync_dsi_panel.xml
+#QDCM calibration xml file for r66451 amoled panel
+PRODUCT_COPY_FILES += hardware/qcom/display/config/qdcm_calib_data_default.xml:$(TARGET_COPY_OUT_VENDOR)/etc/qdcm_calib_data_r66451_amoled_cmd_mode_dsi_visionox_panel_with_DSC.xml
+PRODUCT_COPY_FILES += hardware/qcom/display/config/qdcm_calib_data_default.xml:$(TARGET_COPY_OUT_VENDOR)/etc/qdcm_calib_data_r66451_amoled_cmd_mode_dsi_visionox_60HZ_panel_with_DSC.xml
+PRODUCT_COPY_FILES += hardware/qcom/display/config/qdcm_calib_data_default.xml:$(TARGET_COPY_OUT_VENDOR)/etc/qdcm_calib_data_r66451_amoled_cmd_mode_dsi_visionox_90HZ_panel_with_DSC.xml
+PRODUCT_COPY_FILES += hardware/qcom/display/config/qdcm_calib_data_default.xml:$(TARGET_COPY_OUT_VENDOR)/etc/qdcm_calib_data_r66451_amoled_cmd_mode_dsi_visionox_120HZ_panel_with_DSC.xml
+PRODUCT_COPY_FILES += hardware/qcom/display/config/qdcm_calib_data_default.xml:$(TARGET_COPY_OUT_VENDOR)/etc/qdcm_calib_data_r66451_amoled_video_mode_dsi_visionox_60HZ_panel_with_DSC.xml
+PRODUCT_COPY_FILES += hardware/qcom/display/config/qdcm_calib_data_default.xml:$(TARGET_COPY_OUT_VENDOR)/etc/qdcm_calib_data_r66451_amoled_video_mode_dsi_visionox_90HZ_panel_with_DSC.xml
+PRODUCT_COPY_FILES += hardware/qcom/display/config/qdcm_calib_data_default.xml:$(TARGET_COPY_OUT_VENDOR)/etc/qdcm_calib_data_r66451_amoled_video_mode_dsi_visionox_120HZ_panel_with_DSC.xml
+#QDCM calibration xml file for rm69299 amoled fhd+ panel
+PRODUCT_COPY_FILES += hardware/qcom/display/config/qdcm_calib_data_default.xml:$(TARGET_COPY_OUT_VENDOR)/etc/qdcm_calib_data_rm69299_amoled_fhd+_video_mode_dsi_visionox_panel.xml
+PRODUCT_COPY_FILES += hardware/qcom/display/config/qdcm_calib_data_default.xml:$(TARGET_COPY_OUT_VENDOR)/etc/qdcm_calib_data_rm69299_amoled_fhd+_cmd_mode_dsi_visionox_panel.xml
 
 PRODUCT_PROPERTY_OVERRIDES += \
     persist.demo.hdmirotationlock=false \
@@ -59,7 +70,11 @@
     vendor.display.comp_mask=0 \
     vendor.display.enable_posted_start_dyn=1 \
     vendor.display.enable_optimize_refresh=1 \
-    vendor.display.use_smooth_motion=1
+    vendor.display.use_smooth_motion=1 \
+    debug.sf.enable_advanced_sf_phase_offset=1 \
+    debug.sf.high_fps_late_sf_phase_offset_ns=-4000000 \
+    debug.sf.high_fps_early_phase_offset_ns=-4000000 \
+    debug.sf.high_fps_early_gl_phase_offset_ns=-4000000
 
 # Enable offline rotator for Bengal.
 ifneq ($(TARGET_BOARD_PLATFORM),bengal)
@@ -83,15 +98,7 @@
 
 ifeq ($(TARGET_BOARD_PLATFORM),kona)
 PRODUCT_PROPERTY_OVERRIDES += \
-    debug.sf.enable_gl_backpressure=1 \
-    debug.sf.early_phase_offset_ns=500000 \
-    debug.sf.early_app_phase_offset_ns=500000 \
-    debug.sf.early_gl_phase_offset_ns=3000000 \
-    debug.sf.early_gl_app_phase_offset_ns=15000000 \
-    debug.sf.high_fps_early_phase_offset_ns=6100000 \
-    debug.sf.high_fps_early_gl_phase_offset_ns=6500000 \
-    debug.sf.perf_fps_early_gl_phase_offset_ns=9000000 \
-    debug.sf.phase_offset_threshold_for_next_vsync_ns=6100000
+    debug.sf.enable_gl_backpressure=1
 endif
 
 ifneq ($(PLATFORM_VERSION), 10)
@@ -105,6 +112,7 @@
 PRODUCT_DEFAULT_PROPERTY_OVERRIDES += ro.surface_flinger.wcg_composition_dataspace=143261696
 PRODUCT_DEFAULT_PROPERTY_OVERRIDES += ro.surface_flinger.protected_contents=true
 PRODUCT_DEFAULT_PROPERTY_OVERRIDES += ro.surface_flinger.use_content_detection_for_refresh_rate=true
+PRODUCT_DEFAULT_PROPERTY_OVERRIDES += ro.surface_flinger.set_touch_timer_ms=200
 
 ifneq (,$(filter userdebug eng, $(TARGET_BUILD_VARIANT)))
 # Recovery is enabled, logging is enabled
diff --git a/gralloc/Android.mk b/gralloc/Android.mk
index be1d7e0..fd26c18 100644
--- a/gralloc/Android.mk
+++ b/gralloc/Android.mk
@@ -43,6 +43,7 @@
 LOCAL_C_INCLUDES              := $(common_includes) $(kernel_includes)
 LOCAL_HEADER_LIBRARIES        := display_headers
 LOCAL_SHARED_LIBRARIES        := $(common_libs) libqdMetaData libdl  \
+                                  android.hardware.graphics.common@1.2 \
                                   android.hardware.graphics.mapper@2.0 \
                                   android.hardware.graphics.mapper@2.1 \
                                   android.hardware.graphics.mapper@3.0 \
diff --git a/gralloc/QtiAllocator.cpp b/gralloc/QtiAllocator.cpp
index 1a04237..35145dc 100644
--- a/gralloc/QtiAllocator.cpp
+++ b/gralloc/QtiAllocator.cpp
@@ -42,23 +42,12 @@
 #include "gr_utils.h"
 
 static void get_properties(gralloc::GrallocProperties *props) {
-  char property[PROPERTY_VALUE_MAX];
-  property_get("vendor.gralloc.use_system_heap_for_sensors", property, "1");
-  if (!(strncmp(property, "0", PROPERTY_VALUE_MAX))) {
-    props->use_system_heap_for_sensors = false;
-  }
+  props->use_system_heap_for_sensors =
+      property_get_bool("vendor.gralloc.use_system_heap_for_sensors", 1);
 
-  property_get("vendor.gralloc.disable_ubwc", property, "0");
-  if (!(strncmp(property, "1", PROPERTY_VALUE_MAX)) ||
-      !(strncmp(property, "true", PROPERTY_VALUE_MAX))) {
-    props->ubwc_disable = true;
-  }
+  props->ubwc_disable = property_get_bool("vendor.gralloc.disable_ubwc", 0);
 
-  property_get("vendor.gralloc.disable_ahardware_buffer", property, "0");
-  if (!(strncmp(property, "1", PROPERTY_VALUE_MAX)) ||
-      !(strncmp(property, "true", PROPERTY_VALUE_MAX))) {
-    props->ahardware_buffer_disable = true;
-  }
+  props->ahardware_buffer_disable = property_get_bool("vendor.gralloc.disable_ahardware_buffer", 0);
 }
 
 namespace vendor {
diff --git a/gralloc/QtiMapper4.cpp b/gralloc/QtiMapper4.cpp
index 83591b0..fe12dd0 100644
--- a/gralloc/QtiMapper4.cpp
+++ b/gralloc/QtiMapper4.cpp
@@ -384,6 +384,7 @@
   hidl_cb(err, reserved_region, reserved_size);
   return Void();
 }
+
 Error QtiMapper::DumpBufferMetadata(const private_handle_t *buffer, BufferDump *outBufferDump) {
   outBufferDump->metadataDump.resize(metadata_type_descriptions_.size());
   for (int i = 0; i < static_cast<int>(metadata_type_descriptions_.size()); i++) {
diff --git a/gralloc/QtiMapper4.h b/gralloc/QtiMapper4.h
index 7029d11..9d3b20c 100644
--- a/gralloc/QtiMapper4.h
+++ b/gralloc/QtiMapper4.h
@@ -128,7 +128,7 @@
     std::memcpy(&out[index], &magic_version, sizeof(magic_version));
     index += sizeof(magic_version);
 
-    out[index] = name_size;
+    std::memcpy(&out[index], &name_size, sizeof(name_size));
     index += sizeof(name_size);
 
     std::memcpy(&out[index], bd_info.name.c_str(), bd_info.name.size());
@@ -167,7 +167,8 @@
     std::memcpy(&magic_version, &in[index], sizeof(magic_version));
     index += sizeof(magic_version);
 
-    uint64_t name_size = in[index];
+    uint64_t name_size;
+    std::memcpy(&name_size, &in[index], sizeof(name_size));
     index += sizeof(name_size);
 
     // The second check validates that the size and magic version are correct
diff --git a/gralloc/gr_buf_descriptor.h b/gralloc/gr_buf_descriptor.h
index 32a208a..bd50259 100644
--- a/gralloc/gr_buf_descriptor.h
+++ b/gralloc/gr_buf_descriptor.h
@@ -59,6 +59,7 @@
   void SetName(std::string name) { name_ = name; }
 
   void SetReservedSize(uint64_t reserved_size) { reserved_size_ = reserved_size; }
+
   uint64_t GetUsage() const { return usage_; }
 
   int GetWidth() const { return width_; }
@@ -72,6 +73,7 @@
   uint64_t GetId() const { return id_; }
 
   uint64_t GetReservedSize() const { return reserved_size_; }
+
   std::string GetName() const { return name_; }
 
  private:
diff --git a/gralloc/gr_buf_mgr.cpp b/gralloc/gr_buf_mgr.cpp
index acc12a0..dab3cd5 100644
--- a/gralloc/gr_buf_mgr.cpp
+++ b/gralloc/gr_buf_mgr.cpp
@@ -60,6 +60,7 @@
 static uint64_t getMetaDataSize() {
   return static_cast<uint64_t>(ROUND_UP_PAGESIZE(sizeof(MetaData_t)));
 }
+
 static int validateAndMap(private_handle_t *handle) {
   if (private_handle_t::validate(handle)) {
     ALOGE("%s: Private handle is invalid - handle:%p", __func__, handle);
@@ -505,7 +506,6 @@
       }
       break;
     default:
-      ALOGE("Offset and size in bits unknown for format %d", format);
       break;
   }
 }
@@ -591,9 +591,8 @@
     std::vector<PlaneLayoutComponent> components;
     grallocToStandardPlaneLayoutComponentType(plane_layout[i].component, &plane_info[i].components,
                                               handle->format);
-    plane_info[i].horizontalSubsampling =
-        static_cast<int64_t>(pow(2, plane_layout[i].h_subsampling));
-    plane_info[i].verticalSubsampling = static_cast<int64_t>(pow(2, plane_layout[i].v_subsampling));
+    plane_info[i].horizontalSubsampling = (1ull << plane_layout[i].h_subsampling);
+    plane_info[i].verticalSubsampling = (1ull << plane_layout[i].v_subsampling);
     plane_info[i].offsetInBytes = static_cast<int64_t>(plane_layout[i].offset);
     plane_info[i].sampleIncrementInBits = static_cast<int64_t>(plane_layout[i].step * 8);
     plane_info[i].strideInBytes = static_cast<int64_t>(plane_layout[i].stride_bytes);
@@ -807,6 +806,7 @@
 
   return err;
 }
+
 Error BufferManager::FlushBuffer(const private_handle_t *handle) {
   std::lock_guard<std::mutex> lock(buffer_lock_);
   auto status = Error::NONE;
@@ -956,8 +956,9 @@
     return Error::BAD_BUFFER;
   }
   auto metadata = reinterpret_cast<MetaData_t *>(hnd->base_metadata);
-  descriptor.GetName().copy(metadata->name, descriptor.GetName().size() + 1);
-  metadata->name[descriptor.GetName().size()] = '\0';
+  auto nameLength = std::min(descriptor.GetName().size(), size_t(MAX_NAME_LEN - 1));
+  nameLength = descriptor.GetName().copy(metadata->name, nameLength);
+  metadata->name[nameLength] = '\0';
 
   metadata->reservedRegion.size = descriptor.GetReservedSize();
 
@@ -1015,6 +1016,7 @@
   }
   return Error::NONE;
 }
+
 Error BufferManager::GetReservedRegion(private_handle_t *handle, void **reserved_region,
                                        uint64_t *reserved_region_size) {
   std::lock_guard<std::mutex> lock(buffer_lock_);
@@ -1101,7 +1103,7 @@
       break;
     }
     case (int64_t)StandardMetadataType::CHROMA_SITING:
-      android::gralloc4::encodeChromaSiting(android::gralloc4::ChromaSiting_Unknown, out);
+      android::gralloc4::encodeChromaSiting(android::gralloc4::ChromaSiting_None, out);
       break;
     case (int64_t)StandardMetadataType::DATASPACE:
       Dataspace dataspace;
@@ -1129,50 +1131,60 @@
       android::gralloc4::encodeBlendMode((BlendMode)metadata->blendMode, out);
       break;
     case (int64_t)StandardMetadataType::SMPTE2086: {
-      Smpte2086 mastering_display_values;
-      mastering_display_values.primaryRed = {
-          static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[0][0]) /
-              50000.0f,
-          static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[0][1]) /
-              50000.0f};
-      mastering_display_values.primaryGreen = {
-          static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[1][0]) /
-              50000.0f,
-          static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[1][1]) /
-              50000.0f};
-      mastering_display_values.primaryBlue = {
-          static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[2][0]) /
-              50000.0f,
-          static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[2][1]) /
-              50000.0f};
-      mastering_display_values.whitePoint = {
-          static_cast<float>(metadata->color.masteringDisplayInfo.primaries.whitePoint[0]) /
-              50000.0f,
-          static_cast<float>(metadata->color.masteringDisplayInfo.primaries.whitePoint[1]) /
-              50000.0f};
-      mastering_display_values.maxLuminance =
-          static_cast<float>(metadata->color.masteringDisplayInfo.maxDisplayLuminance);
-      mastering_display_values.minLuminance =
-          static_cast<float>(metadata->color.masteringDisplayInfo.minDisplayLuminance) / 10000.0f;
-      android::gralloc4::encodeSmpte2086(mastering_display_values, out);
+      if (metadata->color.masteringDisplayInfo.colorVolumeSEIEnabled) {
+        Smpte2086 mastering_display_values;
+        mastering_display_values.primaryRed = {
+            static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[0][0]) /
+                50000.0f,
+            static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[0][1]) /
+                50000.0f};
+        mastering_display_values.primaryGreen = {
+            static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[1][0]) /
+                50000.0f,
+            static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[1][1]) /
+                50000.0f};
+        mastering_display_values.primaryBlue = {
+            static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[2][0]) /
+                50000.0f,
+            static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[2][1]) /
+                50000.0f};
+        mastering_display_values.whitePoint = {
+            static_cast<float>(metadata->color.masteringDisplayInfo.primaries.whitePoint[0]) /
+                50000.0f,
+            static_cast<float>(metadata->color.masteringDisplayInfo.primaries.whitePoint[1]) /
+                50000.0f};
+        mastering_display_values.maxLuminance =
+            static_cast<float>(metadata->color.masteringDisplayInfo.maxDisplayLuminance);
+        mastering_display_values.minLuminance =
+            static_cast<float>(metadata->color.masteringDisplayInfo.minDisplayLuminance) / 10000.0f;
+        android::gralloc4::encodeSmpte2086(mastering_display_values, out);
+      } else {
+        android::gralloc4::encodeSmpte2086(std::nullopt, out);
+      }
       break;
     }
     case (int64_t)StandardMetadataType::CTA861_3: {
-      Cta861_3 content_light_level;
-      content_light_level.maxContentLightLevel =
-          static_cast<float>(metadata->color.contentLightLevel.maxContentLightLevel);
-      content_light_level.maxFrameAverageLightLevel =
-          static_cast<float>(metadata->color.contentLightLevel.minPicAverageLightLevel) / 10000.0f;
-      android::gralloc4::encodeCta861_3(content_light_level, out);
+      if (metadata->color.contentLightLevel.lightLevelSEIEnabled) {
+        Cta861_3 content_light_level;
+        content_light_level.maxContentLightLevel =
+            static_cast<float>(metadata->color.contentLightLevel.maxContentLightLevel);
+        content_light_level.maxFrameAverageLightLevel =
+            static_cast<float>(metadata->color.contentLightLevel.minPicAverageLightLevel) /
+            10000.0f;
+        android::gralloc4::encodeCta861_3(content_light_level, out);
+      } else {
+        android::gralloc4::encodeCta861_3(std::nullopt, out);
+      }
       break;
     }
     case (int64_t)StandardMetadataType::SMPTE2094_40: {
-      std::vector<uint8_t> dynamic_metadata_payload;
       if (metadata->color.dynamicMetaDataValid &&
           metadata->color.dynamicMetaDataLen <= HDR_DYNAMIC_META_DATA_SZ) {
+        std::vector<uint8_t> dynamic_metadata_payload;
         dynamic_metadata_payload.resize(metadata->color.dynamicMetaDataLen);
-        memcpy(dynamic_metadata_payload.data(), &metadata->color.dynamicMetaDataPayload,
-               metadata->color.dynamicMetaDataLen);
+        dynamic_metadata_payload.assign(
+            metadata->color.dynamicMetaDataPayload,
+            metadata->color.dynamicMetaDataPayload + metadata->color.dynamicMetaDataLen);
         android::gralloc4::encodeSmpte2094_40(dynamic_metadata_payload, out);
       } else {
         android::gralloc4::encodeSmpte2094_40(std::nullopt, out);
@@ -1307,6 +1319,8 @@
       std::optional<Smpte2086> mastering_display_values;
       android::gralloc4::decodeSmpte2086(in, &mastering_display_values);
       if (mastering_display_values != std::nullopt) {
+        metadata->color.masteringDisplayInfo.colorVolumeSEIEnabled = true;
+
         metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[0][0] =
             static_cast<uint32_t>(mastering_display_values->primaryRed.x * 50000.0f);
         metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[0][1] =
@@ -1331,6 +1345,8 @@
             static_cast<uint32_t>(mastering_display_values->maxLuminance);
         metadata->color.masteringDisplayInfo.minDisplayLuminance =
             static_cast<uint32_t>(mastering_display_values->minLuminance * 10000.0f);
+      } else {
+        metadata->color.masteringDisplayInfo.colorVolumeSEIEnabled = false;
       }
       break;
     }
@@ -1338,10 +1354,13 @@
       std::optional<Cta861_3> content_light_level;
       android::gralloc4::decodeCta861_3(in, &content_light_level);
       if (content_light_level != std::nullopt) {
+        metadata->color.contentLightLevel.lightLevelSEIEnabled = true;
         metadata->color.contentLightLevel.maxContentLightLevel =
             static_cast<uint32_t>(content_light_level->maxContentLightLevel);
         metadata->color.contentLightLevel.minPicAverageLightLevel =
             static_cast<uint32_t>(content_light_level->maxFrameAverageLightLevel * 10000.0f);
+      } else {
+        metadata->color.contentLightLevel.lightLevelSEIEnabled = false;
       }
       break;
     }
@@ -1349,13 +1368,13 @@
       std::optional<std::vector<uint8_t>> dynamic_metadata_payload;
       android::gralloc4::decodeSmpte2094_40(in, &dynamic_metadata_payload);
       if (dynamic_metadata_payload != std::nullopt) {
-        if (dynamic_metadata_payload->size() <= HDR_DYNAMIC_META_DATA_SZ &&
-            dynamic_metadata_payload->size() > 0) {
-          metadata->color.dynamicMetaDataLen = dynamic_metadata_payload->size();
-          memcpy(&metadata->color.dynamicMetaDataPayload, &dynamic_metadata_payload,
-                 metadata->color.dynamicMetaDataLen);
-          metadata->color.dynamicMetaDataValid = true;
-        }
+        if (dynamic_metadata_payload->size() > HDR_DYNAMIC_META_DATA_SZ)
+          return Error::BAD_VALUE;
+
+        metadata->color.dynamicMetaDataLen = dynamic_metadata_payload->size();
+        std::copy(dynamic_metadata_payload->begin(), dynamic_metadata_payload->end(),
+                  metadata->color.dynamicMetaDataPayload);
+        metadata->color.dynamicMetaDataValid = true;
       } else {
         // Reset metadata by passing in std::nullopt
         metadata->color.dynamicMetaDataValid = false;
diff --git a/sdm/libs/core/drm/hw_events_drm.cpp b/sdm/libs/core/drm/hw_events_drm.cpp
index d584738..d3b0129 100644
--- a/sdm/libs/core/drm/hw_events_drm.cpp
+++ b/sdm/libs/core/drm/hw_events_drm.cpp
@@ -563,8 +563,9 @@
 }
 
 void HWEventsDRM::HandleVSync(char *data) {
+  DisplayError ret = kErrorNone;
+  vsync_handler_count_ = 0;  //  reset vsync handler count. lock not needed
   {
-    DisplayError ret = kErrorNone;
     std::lock_guard<std::mutex> lock(vsync_mutex_);
     vsync_registered_ = false;
     if (vsync_enabled_) {
@@ -580,6 +581,16 @@
   if (error != 0) {
     DLOGE("drmHandleEvent failed: %i", error);
   }
+
+  if (vsync_handler_count_ > 1) {
+    //  probable thread preemption caused > 1 vsync handling. Re-enable vsync before polling
+    std::lock_guard<std::mutex> lock(vsync_mutex_);
+    vsync_registered_ = false;
+    if (vsync_enabled_) {
+      ret = RegisterVSync();
+      vsync_registered_ = (ret == kErrorNone);
+    }
+  }
 }
 
 void HWEventsDRM::HandlePanelDead(char *data) {
@@ -625,9 +636,11 @@
 
 void HWEventsDRM::VSyncHandlerCallback(int fd, unsigned int sequence, unsigned int tv_sec,
                                        unsigned int tv_usec, void *data) {
+  HWEventsDRM *ev_data = reinterpret_cast<HWEventsDRM *>(data);
+  ev_data->vsync_handler_count_++;
   int64_t timestamp = (int64_t)(tv_sec)*1000000000 + (int64_t)(tv_usec)*1000;
   DTRACE_SCOPED();
-  reinterpret_cast<HWEventsDRM *>(data)->event_handler_->VSync(timestamp);
+  ev_data->event_handler_->VSync(timestamp);
 }
 
 void HWEventsDRM::HandleIdleTimeout(char *data) {
diff --git a/sdm/libs/core/drm/hw_events_drm.h b/sdm/libs/core/drm/hw_events_drm.h
index c819f9a..659d43a 100644
--- a/sdm/libs/core/drm/hw_events_drm.h
+++ b/sdm/libs/core/drm/hw_events_drm.h
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2017-2018, The Linux Foundation. All rights reserved.
+* Copyright (c) 2017-2018, 2020 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
@@ -102,6 +102,7 @@
   uint32_t histogram_index_ = UINT32_MAX;
   bool vsync_enabled_ = false;
   bool vsync_registered_ = false;
+  uint32_t vsync_handler_count_ = 0;
   std::mutex vsync_mutex_;  // To protect vsync_enabled_ and vsync_registered_
   uint32_t idle_notify_index_ = UINT32_MAX;
   sde_drm::DRMDisplayToken token_ = {};