Merge "gralloc: Remove default color space in AllocateBuffer()" into display.lnx.5.1.r2-rel
diff --git a/gralloc/QtiMapper4.h b/gralloc/QtiMapper4.h
index 7fa27b1..3c5137f 100644
--- a/gralloc/QtiMapper4.h
+++ b/gralloc/QtiMapper4.h
@@ -150,9 +150,7 @@
     std::memcpy(&out[index], &bd_info.usage, sizeof(bd_info.usage));
     index += sizeof(bd_info.usage);
 
-    // Cap the reserved region size at one page (4096 bytes)
-    uint64_t reserved_size = std::min(bd_info.reservedSize, (uint64_t)4096);
-    std::memcpy(&out[index], &reserved_size, sizeof(reserved_size));
+    std::memcpy(&out[index], &bd_info.reservedSize, sizeof(bd_info.reservedSize));
 
     return out;
   }
@@ -266,7 +264,11 @@
       {qtigralloc::MetadataType_FD, "fd from private_handle_t", true, false},
       {qtigralloc::MetadataType_PrivateFlags, "Flags in private_handle_t", true, false},
       {qtigralloc::MetadataType_AlignedWidthInPixels, "width in private_handle_t", true, false},
-      {qtigralloc::MetadataType_AlignedHeightInPixels, "height in private_handle_t", true, false}
+      {qtigralloc::MetadataType_AlignedHeightInPixels, "height in private_handle_t", true, false},
+#ifdef METADATA_V2
+      {qtigralloc::MetadataType_StandardMetadataStatus, "Is standard metadata set", true, false},
+      {qtigralloc::MetadataType_VendorMetadataStatus, "Is vendor metadata set", true, false}
+#endif
   };
 };
 
diff --git a/gralloc/gr_buf_mgr.cpp b/gralloc/gr_buf_mgr.cpp
index e939a62..f0b4639 100644
--- a/gralloc/gr_buf_mgr.cpp
+++ b/gralloc/gr_buf_mgr.cpp
@@ -51,17 +51,30 @@
 using aidl::android::hardware::graphics::common::StandardMetadataType;
 using aidl::android::hardware::graphics::common::XyColor;
 using ::android::hardware::graphics::common::V1_2::PixelFormat;
+
 static BufferInfo GetBufferInfo(const BufferDescriptor &descriptor) {
   return BufferInfo(descriptor.GetWidth(), descriptor.GetHeight(), descriptor.GetFormat(),
                     descriptor.GetUsage());
 }
 
-// duplicate from qdmetadata
-static uint32_t getMetaDataSize() {
-  return static_cast<uint32_t>(ROUND_UP_PAGESIZE(sizeof(MetaData_t)));
+static uint64_t getMetaDataSize(uint64_t reserved_region_size) {
+// Only include the reserved region size when using Metadata_t V2
+#ifndef METADATA_V2
+  reserved_region_size = 0;
+#endif
+  return static_cast<uint64_t>(ROUND_UP_PAGESIZE(sizeof(MetaData_t) +
+                               static_cast<uint32_t>(reserved_region_size)));
 }
 
-static int validateAndMap(private_handle_t *handle) {
+static void unmapAndReset(private_handle_t *handle, uint64_t reserved_region_size = 0) {
+  if (private_handle_t::validate(handle) == 0 && handle->base_metadata) {
+    munmap(reinterpret_cast<void *>(handle->base_metadata),
+           static_cast<uint32_t>(getMetaDataSize(reserved_region_size)));
+    handle->base_metadata = 0;
+  }
+}
+
+static int validateAndMap(private_handle_t *handle, uint64_t reserved_region_size = 0) {
   if (private_handle_t::validate(handle)) {
     ALOGE("%s: Private handle is invalid - handle:%p", __func__, handle);
     return -1;
@@ -72,26 +85,36 @@
   }
 
   if (!handle->base_metadata) {
-    auto size = getMetaDataSize();
-    void *base = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, handle->fd_metadata, 0);
+    uint64_t size = getMetaDataSize(reserved_region_size);
+    void *base = mmap(NULL, static_cast<uint32_t>(size), PROT_READ | PROT_WRITE,
+                      MAP_SHARED, handle->fd_metadata, 0);
     if (base == reinterpret_cast<void *>(MAP_FAILED)) {
       ALOGE("%s: metadata mmap failed - handle:%p fd: %d err: %s", __func__, handle,
             handle->fd_metadata, strerror(errno));
-
       return -1;
     }
     handle->base_metadata = (uintptr_t)base;
+#ifdef METADATA_V2
+    // The allocator process gets the reserved region size from the BufferDescriptor.
+    // When importing to another process, the reserved size is unknown until mapping the metadata,
+    // hence the re-mapping below
+    auto metadata = reinterpret_cast<MetaData_t *>(handle->base_metadata);
+    if (reserved_region_size == 0 && metadata->reservedSize) {
+      size = getMetaDataSize(metadata->reservedSize);
+      unmapAndReset(handle);
+      void *new_base = mmap(NULL, static_cast<uint32_t>(size), PROT_READ | PROT_WRITE, MAP_SHARED, handle->fd_metadata, 0);
+      if (new_base == reinterpret_cast<void *>(MAP_FAILED)) {
+        ALOGE("%s: metadata mmap failed - handle:%p fd: %d err: %s", __func__, handle,
+              handle->fd_metadata, strerror(errno));
+        return -1;
+      }
+      handle->base_metadata = (uintptr_t)new_base;
+    }
+#endif
   }
   return 0;
 }
 
-static void unmapAndReset(private_handle_t *handle) {
-  if (private_handle_t::validate(handle) == 0 && handle->base_metadata) {
-    munmap(reinterpret_cast<void *>(handle->base_metadata), getMetaDataSize());
-    handle->base_metadata = 0;
-  }
-}
-
 static Error dataspaceToColorMetadata(Dataspace dataspace, ColorMetaData *color_metadata) {
   ColorMetaData out;
   uint32_t primaries = (uint32_t)dataspace & (uint32_t)Dataspace::STANDARD_MASK;
@@ -635,14 +658,16 @@
     return Error::BAD_BUFFER;
   }
 
+  auto meta_size = getMetaDataSize(buf->reserved_size);
+
   if (allocator_->FreeBuffer(reinterpret_cast<void *>(hnd->base), hnd->size, hnd->offset, hnd->fd,
                              buf->ion_handle_main) != 0) {
     return Error::BAD_BUFFER;
   }
 
-  auto meta_size = getMetaDataSize();
-  if (allocator_->FreeBuffer(reinterpret_cast<void *>(hnd->base_metadata), meta_size,
-                             hnd->offset_metadata, hnd->fd_metadata, buf->ion_handle_meta) != 0) {
+  if (allocator_->FreeBuffer(reinterpret_cast<void *>(hnd->base_metadata),
+                             static_cast<uint32_t>(meta_size), hnd->offset_metadata,
+                             hnd->fd_metadata, buf->ion_handle_meta) != 0) {
     return Error::BAD_BUFFER;
   }
 
@@ -672,6 +697,23 @@
 void BufferManager::RegisterHandleLocked(const private_handle_t *hnd, int ion_handle,
                                          int ion_handle_meta) {
   auto buffer = std::make_shared<Buffer>(hnd, ion_handle, ion_handle_meta);
+
+  if (hnd->base_metadata) {
+    auto metadata = reinterpret_cast<MetaData_t *>(hnd->base_metadata);
+#ifdef METADATA_V2
+    buffer->reserved_size = metadata->reservedSize;
+    if (buffer->reserved_size > 0) {
+      buffer->reserved_region_ptr =
+          reinterpret_cast<void *>(hnd->base_metadata + sizeof(MetaData_t));
+    } else {
+      buffer->reserved_region_ptr = nullptr;
+    }
+#else
+    buffer->reserved_region_ptr = reinterpret_cast<void *>(&(metadata->reservedRegion.data));
+    buffer->reserved_size = metadata->reservedRegion.size;
+#endif
+  }
+
   handles_map_.emplace(std::make_pair(hnd, buffer));
 }
 
@@ -699,6 +741,12 @@
   hnd->base = 0;
   hnd->base_metadata = 0;
   hnd->gpuaddr = 0;
+
+  if (validateAndMap(hnd)) {
+    ALOGE("Failed to map metadata: hnd: %p, fd:%d, id:%" PRIu64, hnd, hnd->fd, hnd->id);
+    return Error::BAD_BUFFER;
+  }
+
   RegisterHandleLocked(hnd, ion_handle, ion_handle_meta);
   return Error::NONE;
 }
@@ -917,7 +965,7 @@
 
   // Allocate memory for MetaData
   AllocData e_data;
-  e_data.size = getMetaDataSize();
+  e_data.size = static_cast<unsigned int>(getMetaDataSize(descriptor.GetReservedSize()));
   e_data.handle = data.handle;
   e_data.align = page_size;
 
@@ -945,7 +993,12 @@
     setMetaDataAndUnmap(hnd, SET_GRAPHICS_METADATA, reinterpret_cast<void *>(&graphics_metadata));
   }
 
+#ifdef METADATA_V2
+  auto error = validateAndMap(hnd, descriptor.GetReservedSize());
+#else
   auto error = validateAndMap(hnd);
+#endif
+
   if (error != 0) {
     ALOGE("validateAndMap failed");
     return Error::BAD_BUFFER;
@@ -955,14 +1008,18 @@
   nameLength = descriptor.GetName().copy(metadata->name, nameLength);
   metadata->name[nameLength] = '\0';
 
-  metadata->reservedRegion.size = static_cast<uint32_t>(descriptor.GetReservedSize());
-
+#ifdef METADATA_V2
+  metadata->reservedSize = descriptor.GetReservedSize();
+#else
+  metadata->reservedRegion.size =
+     static_cast<uint32_t>(std::min(descriptor.GetReservedSize(), (uint64_t)RESERVED_REGION_SIZE));
+#endif
   metadata->crop.top = 0;
   metadata->crop.left = 0;
   metadata->crop.right = hnd->width;
   metadata->crop.bottom = hnd->height;
 
-  unmapAndReset(hnd);
+  unmapAndReset(hnd, descriptor.GetReservedSize());
 
   *handle = hnd;
 
@@ -1021,14 +1078,12 @@
   auto buf = GetBufferFromHandleLocked(handle);
   if (buf == nullptr)
     return Error::BAD_BUFFER;
-
-  auto err = validateAndMap(handle);
-  if (err != 0)
+  if (!handle->base_metadata) {
     return Error::BAD_BUFFER;
-  auto metadata = reinterpret_cast<MetaData_t *>(handle->base_metadata);
+  }
 
-  *reserved_region = reinterpret_cast<void *>(&(metadata->reservedRegion.data));
-  *reserved_region_size = metadata->reservedRegion.size;
+  *reserved_region = buf->reserved_region_ptr;
+  *reserved_region_size = buf->reserved_size;
 
   return Error::NONE;
 }
@@ -1042,9 +1097,9 @@
   if (buf == nullptr)
     return Error::BAD_BUFFER;
 
-  auto err = validateAndMap(handle);
-  if (err != 0)
+  if (!handle->base_metadata) {
     return Error::BAD_BUFFER;
+  }
 
   auto metadata = reinterpret_cast<MetaData_t *>(handle->base_metadata);
 
@@ -1101,9 +1156,17 @@
       android::gralloc4::encodeChromaSiting(android::gralloc4::ChromaSiting_None, out);
       break;
     case (int64_t)StandardMetadataType::DATASPACE:
-      Dataspace dataspace;
-      colorMetadataToDataspace(metadata->color, &dataspace);
-      android::gralloc4::encodeDataspace(dataspace, out);
+#ifdef METADATA_V2
+      if (metadata->isStandardMetadataSet[GET_STANDARD_METADATA_STATUS_INDEX(metadatatype_value)]) {
+#endif
+        Dataspace dataspace;
+        colorMetadataToDataspace(metadata->color, &dataspace);
+        android::gralloc4::encodeDataspace(dataspace, out);
+#ifdef METADATA_V2
+      } else {
+        android::gralloc4::encodeDataspace(Dataspace::UNKNOWN, out);
+      }
+#endif
       break;
     case (int64_t)StandardMetadataType::INTERLACED:
       if (metadata->interlaced > 0) {
@@ -1254,6 +1317,14 @@
       android::gralloc4::encodeUint32(qtigralloc::MetadataType_AlignedHeightInPixels,
                                       handle->height, out);
       break;
+#ifdef METADATA_V2
+    case QTI_STANDARD_METADATA_STATUS:
+      qtigralloc::encodeMetadataState(metadata->isStandardMetadataSet, out);
+      break;
+    case QTI_VENDOR_METADATA_STATUS:
+      qtigralloc::encodeMetadataState(metadata->isVendorMetadataSet, out);
+      break;
+#endif
     default:
       error = Error::UNSUPPORTED;
   }
@@ -1271,16 +1342,25 @@
   if (buf == nullptr)
     return Error::BAD_BUFFER;
 
-  int err = validateAndMap(handle);
-  if (err != 0)
+  if (!handle->base_metadata) {
     return Error::BAD_BUFFER;
-
+  }
   if (in.size() == 0) {
     return Error::UNSUPPORTED;
   }
 
   auto metadata = reinterpret_cast<MetaData_t *>(handle->base_metadata);
 
+#ifdef METADATA_V2
+  // By default, set these to true
+  // Reset to false for special cases below
+  if (IS_VENDOR_METADATA_TYPE(metadatatype_value)) {
+    metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(metadatatype_value)] = true;
+  } else {
+    metadata->isStandardMetadataSet[GET_STANDARD_METADATA_STATUS_INDEX(metadatatype_value)] = true;
+  }
+#endif
+
   switch (metadatatype_value) {
     // These are constant (unchanged after allocation)
     case (int64_t)StandardMetadataType::BUFFER_ID:
@@ -1345,6 +1425,10 @@
         metadata->color.masteringDisplayInfo.minDisplayLuminance =
             static_cast<uint32_t>(mastering_display_values->minLuminance * 10000.0f);
       } else {
+#ifdef METADATA_V2
+        metadata->isStandardMetadataSet[GET_STANDARD_METADATA_STATUS_INDEX(metadatatype_value)] =
+            false;
+#endif
         metadata->color.masteringDisplayInfo.colorVolumeSEIEnabled = false;
       }
       break;
@@ -1359,6 +1443,10 @@
         metadata->color.contentLightLevel.minPicAverageLightLevel =
             static_cast<uint32_t>(content_light_level->maxFrameAverageLightLevel * 10000.0f);
       } else {
+#ifdef METADATA_V2
+        metadata->isStandardMetadataSet[GET_STANDARD_METADATA_STATUS_INDEX(metadatatype_value)] =
+            false;
+#endif
         metadata->color.contentLightLevel.lightLevelSEIEnabled = false;
       }
       break;
@@ -1376,6 +1464,10 @@
         metadata->color.dynamicMetaDataValid = true;
       } else {
         // Reset metadata by passing in std::nullopt
+#ifdef METADATA_V2
+        metadata->isStandardMetadataSet[GET_STANDARD_METADATA_STATUS_INDEX(metadatatype_value)] =
+            false;
+#endif
         metadata->color.dynamicMetaDataValid = false;
       }
       break;
@@ -1438,8 +1530,17 @@
       qtigralloc::decodeVideoHistogramMetadata(in, &metadata->video_histogram_stats);
       break;
     default:
+#ifdef METADATA_V2
+      if (IS_VENDOR_METADATA_TYPE(metadatatype_value)) {
+        metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(metadatatype_value)] = false;
+      } else {
+        metadata->isStandardMetadataSet[GET_STANDARD_METADATA_STATUS_INDEX(metadatatype_value)] =
+            false;
+      }
+#endif
       return Error::BAD_VALUE;
   }
+
   return Error::NONE;
 }
 
diff --git a/gralloc/gr_buf_mgr.h b/gralloc/gr_buf_mgr.h
index 9c5794c..a3a8c43 100644
--- a/gralloc/gr_buf_mgr.h
+++ b/gralloc/gr_buf_mgr.h
@@ -87,6 +87,8 @@
         : handle(h), ion_handle_main(ih_main), ion_handle_meta(ih_meta) {}
     void IncRef() { ++ref_count; }
     bool DecRef() { return --ref_count == 0; }
+    uint64_t reserved_size = 0;
+    void *reserved_region_ptr = nullptr;
   };
 
   Error FreeBuffer(std::shared_ptr<Buffer> buf);
diff --git a/sdm/libs/core/drm/hw_device_drm.cpp b/sdm/libs/core/drm/hw_device_drm.cpp
index 007cb2a..da5c271 100644
--- a/sdm/libs/core/drm/hw_device_drm.cpp
+++ b/sdm/libs/core/drm/hw_device_drm.cpp
@@ -706,6 +706,9 @@
   // Convert the luminance values to cd/m^2 units.
   hw_panel_info_.peak_luminance = FLOAT(connector_info_.panel_hdr_prop.peak_brightness) / 10000.0f;
   hw_panel_info_.blackness_level = FLOAT(connector_info_.panel_hdr_prop.blackness_level) / 10000.0f;
+  hw_panel_info_.average_luminance = FLOAT(connector_info_.panel_hdr_prop.peak_brightness +
+                                           connector_info_.panel_hdr_prop.blackness_level) /
+                                           (2 * 10000.0f);
   hw_panel_info_.primaries.white_point[0] = connector_info_.panel_hdr_prop.display_primaries[0];
   hw_panel_info_.primaries.white_point[1] = connector_info_.panel_hdr_prop.display_primaries[1];
   hw_panel_info_.primaries.red[0] = connector_info_.panel_hdr_prop.display_primaries[2];